布尔列趋势

完整的代码是:

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 并将其附加为一列。对于假值计数器必须设置为 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

回答

趋势用途:

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

然后将Trues替换为NaNs 并向前填充缺失值:

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


以上是布尔列趋势的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>