完整的代码是:
import pandas as pd
import numpy as np
df = pd.read_excel('C:/Users/Administrator/Documents/Book1.xlsx')
df['boolean'] = df['Prev Close'] < df['Close']
#sample data
df = pd.DataFrame({'boolean' : [False] + [True] + [False] * 2 +
[True] * 3 + [False] + [True]})
print (df)
boolean
0 False
1 True
2 False
3 False
4 True
5 True
6 True
7 False
8 True
如果有多个真值,那么如何依次检查有多少真值,将1添加到Trending计数器并将其作为一列追加。对于false值计数器,必须设置为0。
因此,最终预期的数据将如下所示:
boolean trend
0 False 0
1 True 1
2 False 0
3 False 0
4 True 1
5 True 2
6 True 3
7 False 0
8 True 1
发布于 2020-12-15 06:05:36
供趋势使用:
a = df['boolean']
b = a.cumsum()
df['trend'] = (b-b.mask(a).ffill().fillna(0).astype(int))
boolean trend
0 False 0
1 True 1
2 False 0
3 False 0
4 True 1
5 True 2
6 True 3
7 False 0
8 True 1
详细信息
首次使用Series.cumsum
print (a.cumsum())
0 0
1 1
2 1
3 1
4 2
5 3
6 4
7 4
8 5
Name: boolean, dtype: int32
然后将True
s替换为NaN
s并向前填充缺失的值:
print (b.mask(a).ffill())
0 0.0
1 0.0
2 0.0
3 0.0
4 2.0
5 2.0
6 2.0
7 2.0
8 2.0
9 5.0
10 5.0
Name: boolean, dtype: float64
然后减去b
值
print (b-b.mask(a).ffill())
0 0.0
1 0.0
2 1.0
3 2.0
4 0.0
5 0.0
6 1.0
7 2.0
8 3.0
9 0.0
10 1.0
Name: boolean, dtype: float64
https://stackoverflow.com/questions/65300767
复制相似问题