熊猫数据框任意两列之间的百分比差异

use*_*702 6 python dataframe pandas

我想为任意两个 Pandas 列之间的百分比差异计算定义一个函数。假设我的数据框由以下定义:

R1  R2    R3    R4   R5    R6
 A   B     1     2    3     4
Run Code Online (Sandbox Code Playgroud)

我希望我的计算定义为

df['R7'] = df[['R3','R4']].apply( method call to calculate perc diff)
Run Code Online (Sandbox Code Playgroud)

df['R8'] = df[['R5','R6']].apply(same method call to calculate perc diff)
Run Code Online (Sandbox Code Playgroud)

怎么做?

我在下面试过

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
Run Code Online (Sandbox Code Playgroud)

它给了我错误信息

类型错误: ('() 正好需要 2 个参数 (1 给定)', u'occurred at index CumNetChargeOffs_x')

sop*_*les 6

用最简单的术语来说,这就是你要找的吗?

def percentage_change(col1,col2):
    return ((col2 - col1) / col1) * 100
Run Code Online (Sandbox Code Playgroud)

您可以将其应用于数据框的任何 2 列:

df['a'] = percentage_change(df['R3'],df['R4'])    
df['b'] =  percentage_change(df['R6'],df['R5'])

Out[220]: 
  R1 R2  R3  R4  R5  R6      a     b
0  A  B   1   2   3   4  100.0 -25.0
Run Code Online (Sandbox Code Playgroud)


小智 1

这会给你百分比偏差:

df.apply(lambda row: (row.iloc[0]-row.iloc[1])/row.iloc[0]*100, axis=1)
Run Code Online (Sandbox Code Playgroud)

如果您有两列以上尝试,

df[['R3', 'R5']].apply(lambda row: (row.iloc[0]-row.iloc[1])/row.iloc[0]*100, axis=1)
Run Code Online (Sandbox Code Playgroud)