2017-10-19 54 views
1

我試圖執行:使用條件語句來減去大熊貓DF列標給ValueError異常:一個系列的真值是不確定

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 

如果commission1,我想要的結果:

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

回答

3

使用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 
+0

是numpy的或熊貓這個更有效率? – dirtysocks45

+0

pshep123的解決方案也一樣嗎? – dirtysocks45

+0

是的。這工作太慢但很慢。 – Dark

1

這應做到:

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

+0

這是最給我Pyandonic解決方案,因爲我使用熊貓和Numpy? – dirtysocks45

+0

我不是pythonic代碼的仲裁者,但它工作並且乾淨。我也沒有測試過速度,所以給他們一個鏡頭,看看什麼最適合你。 – pshep123

相關問題