本文介绍了使用条件语句从pandas df列中减去标量会导致ValueError:Series的真值不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行:

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

,然后我得到错误. 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.

例如,df_trades.loc[:, 'CASH']打印出

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

如果commission1,我需要结果:

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

这篇关于使用条件语句从pandas df列中减去标量会导致ValueError:Series的真值不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:02