2 回答
TA贡献1951条经验 获得超3个赞
如果我理解正确,您可以创建要复制的行的辅助数据帧,然后增加该Week辅助数据帧上的数字,然后连接到原始数据:
helper = pd.concat([df.loc[df.Course == 'Prison']]*2)
helper['Week'] += helper.reset_index().index+1
df = pd.concat((df,helper)).sort_values('ID')
>>> df
ID Name Week Course Hours
0 1 John A 1922 Bike Tech 5.5
1 2 John B 1922 Auto Tech 3.2
2 3 John C 1922 Prison 3.5
2 3 John C 1923 Prison 3.5
2 3 John C 1924 Prison 3.5
3 4 John D 1922 Comp 6.5
4 5 John E 1922 Awareness 7.0
5 6 John F 1922 First Aid 7.2
6 7 John G 1922 BasketBall 2.5
7 8 John H 1922 Tech 5.4
TA贡献1817条经验 获得超14个赞
可以传递一行,这是一个pd.Series与您的df. 例如,取
>>> row = df.loc[df.Course.eq('Prison'), :].iloc[0,:].copy()
ID 3
Name John C
Week 1922
Course Prison
Hours 3.5
Name: 2, dtype: object
然后
def duplicate(n, row, df):
week = row['Week']
for i in range(1, n+1):
row['Week'] = week + i
df.loc[-i, :] = row
return df.sort_values('ID').reset_index(drop=True)
>>> duplicate(3, row, df )
ID Name Week Course Hours
0 1.0 John A 1922.0 Bike Tech 5.5
1 2.0 John B 1922.0 Auto Tech 3.2
2 3.0 John C 1922.0 Prison 3.5
3 3.0 John C 1923.0 Prison 3.5
4 3.0 John C 1924.0 Prison 3.5
5 3.0 John C 1925.0 Prison 3.5
6 4.0 John D 1922.0 Comp 6.5
7 5.0 John E 1922.0 Awareness 7.0
8 6.0 John F 1922.0 First Aid 7.2
9 7.0 John G 1922.0 BasketBall 2.5
10 8.0 John H 1922.0 Tech 5.4
添加回答
举报