我在“python pandas”中有一个 bool 掩码,我想在其中加宽(涂抹?)每个“真”样本。假设我有以下内容:
import pandas
data = pandas.DataFrame({'col1': [False, True, False, False, False, False, True, False, False, False]})
所以“真”面具看起来像:
mask = data[data.col1 == True]
>>> mask
col1
1 True
6 True
我想要:
>>> mask
col1
0 True
1 True
2 True
5 True
6 True
7 True
如何将相邻索引的距离设置为(比如)1 到“True”?我可以写一个 for 循环,没有什么。但这感觉不对。
提示?尖端?关键词?
谢谢!
请您参考如下方法:
一种方法是使用rolling 和max:
n=1
window = n*2 + 1
data.col1.rolling(window, center=True, min_periods=1).max().astype(bool)
输出:
0 True
1 True
2 True
3 False
4 False
5 True
6 True
7 True
8 False
9 False
Name: col1, dtype: bool
print(mask)
col1
0 True
1 True
2 True
5 True
6 True
7 True
