2016-04-22 15 views
0

大きなデータセットで作業しています。同じ列の次の行の値が現在の値よりも大きいかどうかを確認する必要があります。次に、1または-1を保存します。したがって、col dの現在の行が1で、同じcolの次の値が2の場合、同じ行と同じデータフレーム内の新しい列( 'e)に1を保存します。問題は、常に単一の値を保存することです。DataFrameで正しい値が保存されない

import numpy as np 
import pandas as pd 

df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd']) 
mask = df1.applymap(lambda x: x <-0.7) 
df1 = df1[-mask.any(axis=1)] 
sLength = len(df1['a']) 


rwno=0 
PrevClose=[] 
for index,row in df1.iterrows(): 
    Close=row.iloc[3] 
    PrevClose.append(Close) 
    rwno+=1 


print df1 
rwno=1 
for index,row in df1.iterrows(): 
    NxtDaySpy=0 
    if rwno < len(df1.index) : 
     NextClose=PrevClose[rwno] 
     Close=row.iloc[3] 
     df1['e']=pd.Series((NextClose-Close)/abs(NextClose-Close), index=df1.index) 

    rwno+=1 


print df1.head 

答えて

1

簡単にするために、1つの列のデータフレームがあるとします。

np.random.seed(14) # so you can reproduce 
df = pd.DataFrame(np.random.randn(10, 1), columns=['a']) 
df.head() 

--------- 
a 
--------- 
1.331587 
1.331587 
0.715279 
-1.545400 
-0.008384 
0.621336 

shift()を使用すると、データを遅らせることができます。

df['a_new'] = df.shift(periods=1).fillna(0.0) 
df.head() 

--------------------- 
a   a_new 
--------------------- 
1.331587 0.000000 
0.715279 1.331587 
-1.545400 0.715279 
-0.008384 -1.545400 
0.621336 -0.008384 

は、その後、あなたの1年代と-1年代を取得するには、リストの内包表記を使用します。

df['a_flags'] = [1 if x > y else -1 for x, y in zip(df.a, df.a_new)] 
df.head() 

------------------------------- 
a   a_new  a_flag 
------------------------------- 
1.331587 0.000000 1 
0.715279 1.331587 -1 
-1.545400 0.715279 -1 
-0.008384 -1.545400 1 
0.621336 -0.008384 1 
+0

私は少し違った方法でこのロジックを使用しましたが、これは完璧に機能しました。 – newtooca

関連する問題