pandas :根据其他列乘以列 [英] pandas: multiply column depending on other column
本文介绍了 pandas :根据其他列乘以列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含 a 和 b 列的数据框.如果 b 为真,我想将列 a 与值 x 相乘,如果 b 为假,则将值 y 相乘.实现这一目标的最佳方法是什么?
I have a dataframe with column a and b. I want to multiply column a with value x if b is true and with value y if b is false. What is the best way to achieve this?
推荐答案
你可以分两步完成:
df.loc[df.b, 'a'] *= x
df.loc[df.b == False, 'a'] *= y
或者在 1 步中使用 where
:
Or in 1 step using where
:
In [366]:
df = pd.DataFrame({'a':randn(5), 'b':[True, True, False, True, False]})
df
Out[366]:
a b
0 0.619641 True
1 -2.080053 True
2 0.379665 False
3 0.134897 True
4 1.580838 False
In [367]:
df.a *= np.where(df.b, 5,10)
df
Out[367]:
a b
0 3.098204 True
1 -10.400266 True
2 3.796653 False
3 0.674486 True
4 15.808377 False
这篇关于 pandas :根据其他列乘以列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文