熊猫:如何检查在另一列特定值之后是否存在一系列正值

时间:2019-02-20 10:22:28

标签: python pandas

我的数据框如下:

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个...非常欢迎任何帮助!谢谢

1 个答案:

答案 0 :(得分:1)

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