我想为任意两个 pandas 列之间的百分比差异计算定义一个函数。假设我的数据框定义为:
R1 R2 R3 R4 R5 R6
A B 1 2 3 4
我希望我的计算定义为
df['R7'] = df[['R3','R4']].apply( method call to calculate perc diff)
和
df['R8'] = df[['R5','R6']].apply(same method call to calculate perc diff)
我怎样才能做到这一点?
我在下面尝试过
df['perc_cnco_error'] = df[['CumNetChargeOffs_x','CumNetChargeOffs_y']].apply(lambda x,y: percCalc(x,y))
def percCalc(x,y):
if x<1e-9:
return 0
else:
return (y - x)*100/x
它给了我错误信息
TypeError: (‘() 恰好接受 2 个参数(给定 1 个)’,u’发生在索引 CumNetChargeOffs_x’)
原文由 user1124702 发布,翻译遵循 CC BY-SA 4.0 许可协议
用最简单的话来说:
您可以将它应用于数据框的任意两列:
等价地使用
pandas
算术运算函数pandas.sub
pandas.div
pandas.mul
您还可以利用
pandas
内置pct_change
计算所有传递的列的百分比变化,并选择要返回的列:设置: