2016-04-18 7 views
1

誰かが私を助けることができますか?私がやろうとしています何Python:新しいPandasデータフレームの列を既存の列のデータで埋め込む方法

import pandas as pd 

testdf = pd.read_csv('../../IBM.csv') 

print testdf 
print "------------" 
testdf['NHigh'] = 0 
print testdf 

if testdf['Close'] > testdf['Open']: 
    testdf['Nhigh'] = testdf['Close'] * testdf['High'] 

print "********" 
print tested 

が、条件が真である場合にのみ、2つの 既存の列の値が移入新しい列を作成している:私は、次のコードから

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() 

を取得しています。

形状は、次の列と在庫データフレームである - Close場合 間の動作に基づいてOpen, High, Low, Closeなどと私は新しい列(NHigh)を追加したいですCloseHighを言う>その行のHighより。

おかげであなたは....

答えて

1

を助けることができる場合、私はあなたがlocfillnaを使用することができると思う:

print testdf 
         Open High  Low Close Volume 
Date_Time             
1997-02-03 09:04:00 3046.0 3048.5 3046.0 3047.5  505 
1997-02-03 09:27:00 3043.5 3043.5 3043.0 3043.0  56 
1997-02-03 09:28:00 3043.0 3044.0 3043.0 3044.0  32 
1997-02-03 09:29:00 3044.5 3044.5 3044.5 3044.5  63 
1997-02-03 09:30:00 3045.0 3045.0 3045.0 3045.0  28 
1997-02-03 09:31:00 3045.0 3045.5 3045.0 3045.5  75 

print testdf['Close'] > testdf['Open']    
Date_Time 
1997-02-03 09:04:00  True 
1997-02-03 09:27:00 False 
1997-02-03 09:28:00  True 
1997-02-03 09:29:00 False 
1997-02-03 09:30:00 False 
1997-02-03 09:31:00  True 
dtype: bool 

testdf.loc[testdf['Close'] > testdf['Open'],'Nhigh'] = testdf['Close'] * testdf['High'] 
testdf['Nhigh'] = testdf['Nhigh'].fillna(0) 
print testdf 
         Open High  Low Close Volume  Nhigh 
Date_Time                
1997-02-03 09:04:00 3046.0 3048.5 3046.0 3047.5  505 9290303.75 
1997-02-03 09:27:00 3043.5 3043.5 3043.0 3043.0  56  0.00 
1997-02-03 09:28:00 3043.0 3044.0 3043.0 3044.0  32 9265936.00 
1997-02-03 09:29:00 3044.5 3044.5 3044.5 3044.5  63  0.00 
1997-02-03 09:30:00 3045.0 3045.0 3045.0 3045.0  28  0.00 
1997-02-03 09:31:00 3045.0 3045.5 3045.0 3045.5  75 9275070.25 

他のソリューションの使用numpy.where

testdf['Nhigh']=np.where(testdf['Close'] > testdf['Open'], testdf['Close']*testdf['High'], 0) 
print testdf 
         Open High  Low Close Volume  Nhigh 
Date_Time                
1997-02-03 09:04:00 3046.0 3048.5 3046.0 3047.5  505 9290303.75 
1997-02-03 09:27:00 3043.5 3043.5 3043.0 3043.0  56  0.00 
1997-02-03 09:28:00 3043.0 3044.0 3043.0 3044.0  32 9265936.00 
1997-02-03 09:29:00 3044.5 3044.5 3044.5 3044.5  63  0.00 
1997-02-03 09:30:00 3045.0 3045.0 3045.0 3045.0  28  0.00 
1997-02-03 09:31:00 3045.0 3045.5 3045.0 3045.5  75 9275070.25 
関連する問題