问题
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