Using conditional statement to subtract scalar from pandas df column gives ValueError: The truth value of a Series is ambiguous
Using conditional statement to subtract scalar from pandas df column gives ValueError: The truth value of a Series is ambiguous
我正在尝试执行:
if df_trades.loc[:, 'CASH'] != 0: df_trades.loc[:, 'CASH'] -= commission
然后我得到了错误。 df_trades.loc[:, 'CASH']
是一列浮点数。我想从该列的每个条目中减去标量 commission
。
例如,df_trades.loc[:, 'CASH']
打印出
2011-01-10 -2557.0000
2011-01-11 0.0000
2011-01-12 0.0000
2011-01-13 -2581.0000
如果commission
是1
,我要结果:
2011-01-10 -2558.0000
2011-01-11 0.0000
2011-01-12 0.0000
2011-01-13 -2582.0000
使用np.where
commission = -1
df['CASH'] = np.where(df['CASH'] != 0, df['CASH'] + commission , df['CASH'])
或 df.where
即
df['CASH'] = df['CASH'].where(df['CASH'] == 0,df['CASH']+commission)
或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
应该这样做:
df.loc[df['CASH'] != 0, 'CASH'] -= 1
我正在尝试执行:
if df_trades.loc[:, 'CASH'] != 0: df_trades.loc[:, 'CASH'] -= commission
然后我得到了错误。 df_trades.loc[:, 'CASH']
是一列浮点数。我想从该列的每个条目中减去标量 commission
。
例如,df_trades.loc[:, 'CASH']
打印出
2011-01-10 -2557.0000
2011-01-11 0.0000
2011-01-12 0.0000
2011-01-13 -2581.0000
如果commission
是1
,我要结果:
2011-01-10 -2558.0000
2011-01-11 0.0000
2011-01-12 0.0000
2011-01-13 -2582.0000
使用np.where
commission = -1
df['CASH'] = np.where(df['CASH'] != 0, df['CASH'] + commission , df['CASH'])
或 df.where
即
df['CASH'] = df['CASH'].where(df['CASH'] == 0,df['CASH']+commission)
或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
应该这样做:
df.loc[df['CASH'] != 0, 'CASH'] -= 1