pandas: multiply column depending on other column

别来无恙 提交于 2021-02-05 07:59:05

问题


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?


回答1:


You could do it in 2 steps:

df.loc[df.b, 'a'] *= x
df.loc[df.b == False, 'a'] *= y

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


来源:https://stackoverflow.com/questions/25196528/pandas-multiply-column-depending-on-other-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!