代码之家  ›  专栏  ›  技术社区  ›  Amruth Raj

更改python系列的相邻元素

  •  0
  • Amruth Raj  · 技术社区  · 1 年前

    我有一个python系列,它有布尔值。只要序列中有True,我希望前5个值和后6个值都是True。

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

    2 回复  |  直到 1 年前
        1
  •  1
  •   dankal444    1 年前

    这是一个使用卷积的小技巧。如果你打算使用它,请添加一些注释,说明这部分代码对未来读者的作用。

    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

        2
  •  0
  •   charles    1 年前

    这是另一种可能的解决方案,包括:

    1. 确定哪些指数具有 True
    2. 迭代每个值并调整相邻值
    x = np.array([
        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]).astype(bool)
    
    # step 1: find indices where entries are True
    true_indices = [i for i, value in enumerate(s) if value]
    
    # step 2: adjust neighboring values
    for idx in true_indices:
        s[max(0, idx-5):min(len(s), idx+7)] = True
    

    感谢@dankal444的小例子:)

    推荐文章