我正在尝试执行以下操作:我有一个由四列组成的数据框。我按column0对框架进行分组,然后在分组的对象上调用一个函数,以在每个组中添加另一列。但是,当我尝试在分组对象上调用函数时,出现错误。我的代码如下所示:
def function(x):
return x['column2']-x['column1']
Groupeddf = df.groupby('column0')
for key, group in Groupeddf:
Nullgroup=group[group.column3 == 0]
Nullgroup['new_column']=Nullgroup.apply(function, axis=1)
当我尝试代码时,我得到 ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series
我的数据框具有以下类型:
column0 column1 column2 column3
0 a 2 5 1
1 a 3 7 0
2 b 1 3 4
3 c 3 5 0
有谁知道如何解决这个问题?
def f(x):
x.loc[x.column3 == 0, 'new_column'] = x['column2'] - x['column1']
return x
print df.groupby('column0').apply(f)
column0 column1 column2 column3 new_column
0 a 2 5 1 NaN
1 a 3 7 0 4
2 b 1 3 4 NaN
3 c 3 5 0 2
但也许groupby
可以省略:
df.loc[df.column3 == 0, 'new_column'] = df['column2'] - df['column1']
print df
column0 column1 column2 column3 new_column
0 a 2 5 1 NaN
1 a 3 7 0 4
2 b 1 3 4 NaN
3 c 3 5 0 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句