更改 python 系列的相邻元素

问题描述 投票:0回答:1

我有一个带有布尔值的Python系列。只要系列中有 True,我就希望前 5 个值和后 6 个值都为 true。

我可以使用 for 循环来实现它,但我想知道是否可以使用内置函数来实现它。

python performance rolling-computation
1个回答
0
投票

这有点像黑客,使用卷积。如果您打算使用它,请为未来的读者添加一些注释,说明这部分代码的作用。

import pandas as pd
import numpy as np


the_series = pd.DataFrame({'series': [0, 1, 0, 0, 0,
                                      0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0,
                                      1, 1, 1, 1, 1,
                                      0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0,
                                      0, 0, 0, 1, 1]})['series'] == 1

result = np.convolve(the_series, np.arange(13), mode='same') > 0
combined_df = pd.DataFrame({'the_series': the_series, 'result': result})

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.