【问题标题】:building a specific sequence with python numpy使用 python numpy 构建特定序列
【发布时间】:2017-05-04 22:59:25
【问题描述】:

您好,我有两个数组,如下所示。

1) 由 1 和 0 组成的数组。1 表示活动日,0 表示节假日。

2) 与数组 1 相比长度更小的等差数列。

结果数组需要是 1) 和 2) 的组合,其中等差数列需要跟随 1 的位置。换句话说,数组 2 需要扩展为数组 1 的长度,并在与数组 1 相同的位置插入 0。

我可以解决这个问题的一种方法是使用带有 slice 的 numpy.insert。但是,由于长度不同并且数组 1 是动态的,我需要一种有效的方法来实现这一点。

谢谢

【问题讨论】:

    标签: python arrays numpy scipy


    【解决方案1】:

    另一种单线解决方案

    设置

    binary = np.array([1, 1, 0, 1, 0, 1, 1, 0, 1, 0])
    arithmetic = np.arange(1, 7)
    

    解决方案

    #find 1s from binary and set values from arithmetic
    binary[np.where(binary>0)] = arithmetic
    
    Out[400]: array([1, 2, 0, 3, 0, 4, 5, 0, 6, 0])
    

    【讨论】:

      【解决方案2】:

      创建正确长度的结果数组(len(binary))填充0,然后使用binary数组作为掩码分配到结果数组中。确保 binary 掩码属于 bool dtype。

      >>> binary = np.array([1, 1, 0, 1, 0, 1, 1, 0, 1, 0], dtype=bool)
      >>> arithmetic = np.arange(1, 7)
      >>> result = np.zeros(len(binary), dtype=arithmetic.dtype)
      >>> result[binary] = arithmetic
      >>> result
      array([1, 2, 0, 3, 0, 4, 5, 0, 6, 0])
      

      【讨论】:

        【解决方案3】:

        另一种方法是创建二进制数组的副本并用算术数组替换所有非零值

        seq = np.arange(1, len(bi_arr[bi_arr != 0])+1)
        
        final_result = bi_arr.copy()
        
        final_result[final_result != 0] = seq
        

        打印(最终结果)

        array([1, 2, 0, 3, 0, 4, 5, 0, 6, 0])
        

        bi-arr 保持不变

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-12-06
          • 1970-01-01
          • 1970-01-01
          • 2014-01-16
          • 1970-01-01
          • 2016-09-02
          • 1970-01-01
          相关资源
          最近更新 更多