【问题标题】:Is there a way to add the first element of one array to the first two elements of another array using iteration in python?有没有办法使用python中的迭代将一个数组的第一个元素添加到另一个数组的前两个元素?
【发布时间】:2020-09-07 20:43:47
【问题描述】:

我想把两个数组的元素加在一起,一个叫propensity shape = (4,) and length = 4 另一个叫state_change_lambda with shape (3,) and length 3

但我想将state_change_lambda 的第一个元素添加到propensity 的第一个和第二个元素,然后像正常迭代一样继续添加元素。

类似:

propensity = np.array([1, 2, 3, 4,])
state_change_lambda = np.array([5, 6, 7])
[out]: new_array_after_addition = ([6, 7, 9, 11]) <-- five has been added to both element 1 and 2 of propensity 

只是我不太确定如何在 python 中执行此操作,我已经查看了enumerate,但我不确定这是完全正确的使用方法

干杯

【问题讨论】:

    标签: python arrays numpy loops


    【解决方案1】:

    你可以特别对待第一个添加,其余的通过一个视图来处理:

    propensity[0] += state_change_lambda[0]
    propensity[1:] += state_change_lambda
    

    如果您不想就地增加propensity,您有一些选择。

    一种方法是添加扩展数组:

    result = propensity + np.concatenate((state_change_lambda[:1], state_change_lambda))
    

    另一种方式(我个人更喜欢,是预先分配结果并存储到其中:

    result = propensity.copy()
    result[0] += state_change_lambda[0]
    result[1:] += state_change_lambda
    

    【讨论】:

      【解决方案2】:

      这可以通过使用两个数组的长度差来完成:

      propensity = np.array([1, 2, 3, 4,])
      state_change_lambda = np.array([5, 6, 7])
      
      length = len(propensity) - len(state_change_lambda) + 1
      for i in range(len(propensity)):
          if i < length:
              propensity[i] += state_change_lambda[0]
          else:
              propensity[i] += state_change_lambda[i-length+1]
      

      【讨论】:

      • 谢谢!两种解决方案都有效,但我试图避免使用很多循环
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 2011-11-04
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多