我需要更新与选择条件匹配的列的值,并连续重复几次。 例如:
输入:
df = pd.DataFrame({"a" : [True,False,False,False,False,True,False,False]})
将值滚动到下3个索引 (input format)
输出:
output = pd.DataFrame({"a" : [True,True,True, False, False, False, True, True, True]}
我查看了pandas.series.repeat,但这增加了新的价值。我需要确保大小保持不变。
答案 0 :(得分:0)
您可以像这样使用while和for循环:
i = 0 // index
content = 'true' // set content to replace
while (i < 3): // run 3 times
for x in dataframe:
dataframe['column'] = dataframe['column'].replace(content, str(i)) // replace content at index i
i = i + 1 // add 1 to index
通过这种方式,您可以只循环前三个索引,而替换某个索引处的值。
答案 1 :(得分:0)
使用.rolling(...)
获取滚动窗口:
df.rolling(window=3, min_periods=1).agg(lambda x: any(x)).astype("bool")
输出:
a
0 True
1 True
2 True
3 False
4 False
5 True
6 True
7 True