簡體   English   中英

Pandas:如何檢查在另一個列特定值之后是否有一系列正值

[英]Pandas: how to check if there is a series of positive values after another column specific value

我的數據框如下所示:

time                    price               macd    signal          macd_histogram  cross
25  2019-01-01 11:38:45 0.00224311  2.502858e-06    2.502858e-06    0.000000e+00    D
26  2019-01-01 11:39:15 0.00224473  2.664147e-06    2.535116e-06    1.290311e-07    D
27  2019-01-01 11:39:30 0.00224422  2.722738e-06    2.572640e-06    1.500983e-07    R
28  2019-01-01 11:40:15 0.00224899  3.095925e-06    2.677297e-06    4.186282e-07    D
29  2019-01-01 11:40:15 0.00224697  3.203015e-06    2.782441e-06    4.205739e-07    D
30  2019-01-01 11:42:00 0.00224668  3.229429e-06    2.871838e-06    3.575910e-07    D
31  2019-01-01 11:45:00 0.00224967  3.438117e-06    2.985094e-06    4.530229e-07    D
32  2019-01-01 11:48:30 0.00224967  3.563519e-06    3.100779e-06    4.627398e-07    R
33  2019-01-01 11:52:30 0.00224983  3.634026e-06    3.207429e-06    4.265979e-07    D
34  2019-01-01 11:52:45 0.00225143  3.768580e-06    3.319659e-06    4.489214e-07    D

我需要的是對於列cross每個等於 R 的值,檢查列macd_histogram中接下來的 5 個值(從同一索引開始)是正還是負。 我不知道如何繼續,特別是檢查接下來的 5 ......任何幫助都非常受歡迎! 謝謝

df = pd.DataFrame({'col': ['D', 'D', 'R', 'D', 'D', 'D', 'D', 'R', 'D', 'D', 'D'], 'col2': [0, -1, 0, 1, 2, 0, 1, 2, -3, 1, 2]})

index = df[df['col'] == 'R'].index.values
df['output'] = False
print(index)

for i in index:
    macd_histogram_list = df.loc[i:i+4, 'col2'].tolist()
    print(macd_histogram_list)
    if all(j >= 0 for j in macd_histogram_list):
        df.loc[i:i+4, 'output'] = True # positive
        continue
    if all(j < 0 for j in macd_histogram_list):
        df.loc[i:i+4, 'output'] = True # negative

print(df)

輸出:

   col  col2  output
0    D     0   False
1    D    -1   False
2    R     0    True
3    D     1    True
4    D     2    True
5    D     0    True
6    D     1    True
7    R     2   False
8    D    -3   False
9    D     1   False
10   D     2   False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM