我的df(使用熊猫):
Value Class
1 False
5 False
7 False
2 False
4 False
3 True
2 False
如果一行的Class为True,那么我还要将前n行全部设置为true。假设n = 3,则所需的输出为:
Value Class
1 False
5 False
7 True
2 True
4 True
3 True
2 False
我查找了类似的问题,但它们似乎专注于添加新列。我想避免这种情况,而只需更改现有值的值即可。我的知识很有限,所以我不知道该如何解决。
答案 0 :(得分:2)
想法是用Series.where
将False
替换为缺失值,然后使用Series.bfill
的limit
参数使用回填功能,最后将缺失值替换为False
并将值转换为布尔值:
n = 3
df['Class'] = df['Class'].where(df['Class']).bfill(limit=n).fillna(0).astype(bool)
print (df)
Value Class
0 1 False
1 5 False
2 7 True
3 2 True
4 4 True
5 3 True
6 2 False