简体   繁体   English

如何根据条件替换熊猫数据框中的值?

[英]How to replace values in a pandas dataframe based on conditions?

I attempt to apply a different formula to a new column "result" based on the column 'C' containing the condition. 我尝试基于包含条件的列“ C”将不同的公式应用于新列“结果”。 If C is 'add' then I would like to add X and Y. When C is 'mult' the result should be X * Y. 如果C为'add',那么我想添加X和Y。当C为'mult'时,结果应为X *Y。

df = pd.DataFrame({'X': [0, 1, 2, 3, 4],
                   'Y': [5, 6, 7, 8, 9],
                   'C': ['add', 'add', 'mult', 'mult', 'mult']})
df['result'] = df['X'] * df['Y']

df.loc[df.C =='add', 'result'] = df.loc[df['C'] =='add', 'X'] \
                                 + df.loc[df['C'] =='add', 'Y']
df

The result I get is: 我得到的结果是:

      C  X  Y  result
0   add  0  5       5
1   add  1  6       5
2  mult  2  7      14
3  mult  3  8      24
4  mult  4  9      36

What I need is 'result' in row 1 being 7 我需要的是第一行的“结果”为7

      C  X  Y  result
0   add  0  5       5
1   add  1  6       7
2  mult  2  7      14
3  mult  3  8      24
4  mult  4  9      36

your code gives right results, but if you want a direct way 您的代码给出了正确的结果,但是如果您想要直接的方法

df['result'] = df.apply(lambda x :  x['X']+x['Y'] if x['C'] == 'add' else x['X']*x['Y'], axis=1 ) 

output : 输出:

   X  Y     C  result
0  0  5   add       5
1  1  6   add       7
2  2  7  mult      14
3  3  8  mult      24
4  4  9  mult      36

Your solution working nice, also is posible use this alternative with numpy.where : 您的解决方案效果很好,也可以在numpy.where使用此替代numpy.where

mask = df.C =='add'
df['result'] = np.where(mask, df['X'] + df['Y'], df['X'] * df['Y'])        
print (df)

   X  Y     C  result
0  0  5   add       5
1  1  6   add       7
2  2  7  mult      14
3  3  8  mult      24
4  4  9  mult      36

If more conditions is possible use numpy.select : 如果有更多条件,请使用numpy.select

m1 = df.C =='add'
m2 = df.C =='mult'
m3 = df.C =='div'
v1 = df['X'] + df['Y']
v2 = df['X'] * df['Y']
v3 = df['X'] / df['Y']

df['result'] = np.select([m1, m2, m3], [v1, v2, v3])        
print (df)

   X  Y     C     result
0  0  5   add   5.000000
1  1  6   add   7.000000
2  2  7  mult  14.000000
3  3  8  mult  24.000000
4  4  9   div   0.444444

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM