首先,我需要使用“设置”列中的唯一值对行进行过滤/分组,然后为每个过滤器/组数据创建相同的2行
df = pd.DataFrame(np.array([[1, 2, 1, 'yes'], [1, 1, 0, 'no'],[1, 3, 0, 'no'],[2, 1, 0,'no'],[2, 2, 0,'yes'], [2, 3, 1,'no'], [3, 3, 1,'no'],[3, 1, 1,'no'],[3, 2, 1, 'no']]),
columns=['a', 'b', 'c', 'set'])
df
groups = df.groupby("set")
for name, group in groups:
group= group.append({'a' : 12 , 'b' : 7, 'set' : name, }, ignore_index=True)
group=group.append({'a' : 12 , 'b' : 8, 'set' : name, }, ignore_index=True)
尝试使用apply
:
def addRows(x):
# <new_rows> write your values
x = x.append(new_rows)
df.groupby('set').apply(addRows).reset_index(drop=True)
编辑:
def addRows(x):
x = x.append({'a' : 12 , 'b' : 7, 'set' : 'name', }, ignore_index=True)
x = x.append({'a' : 12 , 'b' : 8, 'set' : 'name', }, ignore_index=True)
return x # <--- need to return
df.groupby('set').apply(addRows).reset_index(drop=True)
a b c set
0 1 1 0 no
1 1 3 0 no
2 2 1 0 no
3 2 3 1 no
4 3 3 1 no
5 3 1 1 no
6 3 2 1 no
7 12 7 NaN name
8 12 8 NaN name
9 1 2 1 yes
10 2 2 0 yes
11 12 7 NaN name
12 12 8 NaN name
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句