Using conditional statement to subtract scalar from pandas df column gives ValueError: The truth value of a Series is ambiguous

醉酒当歌 提交于 2019-12-12 20:09:35

问题


I'm trying to execute:

if df_trades.loc[:, 'CASH'] != 0: df_trades.loc[:, 'CASH'] -= commission

and then I get the error. df_trades.loc[:, 'CASH'] is a column of floats. I want to subtract the scalar commission from each entry in that column.

For example, df_trades.loc[:, 'CASH'] prints out

2011-01-10   -2557.0000
2011-01-11       0.0000
2011-01-12       0.0000
2011-01-13   -2581.0000

If commission is 1, I want the result:

2011-01-10   -2558.0000
2011-01-11       0.0000
2011-01-12       0.0000
2011-01-13   -2582.0000

回答1:


Use np.where

commission = -1
df['CASH'] = np.where(df['CASH'] != 0, df['CASH'] + commission , df['CASH'])

or df.where i.e

df['CASH'] = df['CASH'].where(df['CASH'] == 0,df['CASH']+commission)

or df.mask

df['CASH'] = df['CASH'].mask(df['CASH'] != 0 ,df['CASH']+commission)
Date
2011-01-10   -2558.0
2011-01-11       0.0
2011-01-12       0.0
2011-01-13   -2582.0
Name: CASH, dtype: float64
%%timeit
commission = -1
df['CASH'] = np.where(df['CASH'] != 0, df['CASH'] + commission , df['CASH'])
1000 loops, best of 3: 750 µs per loop

%%timeit
df['CASH'].mask(df['CASH'] != 0 ,df['CASH']+commission)
1000 loops, best of 3: 1.45 ms per loop

%%timeit
df['CASH'].where(df['CASH'] == 0,df['CASH']+commission)
1000 loops, best of 3: 1.55 ms per loop

%%timeit
df.loc[df['CASH'] != 0, 'CASH'] += commission
100 loops, best of 3: 2.37 ms per loop



回答2:


This should do it:

df.loc[df['CASH'] != 0, 'CASH'] -= 1



来源:https://stackoverflow.com/questions/46830344/using-conditional-statement-to-subtract-scalar-from-pandas-df-column-gives-value

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