我的 df(使用 pandas):
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
我查找过类似的问题,但他们似乎专注于添加新列。我想避免这种情况,只是改变现有值。我的知识非常有限,所以我不知道如何解决这个问题。
最佳答案
想法是将False
替换为Series.where
缺失值然后使用带有 limit
参数的回填函数 Series.bfill
,最后将缺失值替换为 False 并将值转换为 bool 值:
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
关于python-3.x - python : How to set n previous rows as True if row x is True in a DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61437113/