【问题标题】:Rearranging 2 arrays with different lengths to create a third array Numpy Python重新排列 2 个不同长度的数组以创建第三个数组 Numpy Python
【发布时间】:2021-11-13 12:57:41
【问题描述】:

我在ab 下面有2 个数组,它们组合成resulta 乘以 a_multiplierb 乘以 b_multiplierab 具有不同长度的数组,我想将它们组合和相乘,然后按照 a*a_multiplier, b*b_multiplier,a*a_multiplier..... 的顺序重新排列它们。如何修改 result 函数以使预期输出起作用?

import numpy as np 

a_multiplier = 3
b_multiplier = 5

a = np.array([5,32,1,4,3])
b = np.array([1,5,11,3])

result = np.vstack([a * a_multiplier, b * b_multiplier]).flatten("F")

预期输出:

[15  5 96 25  3 55 12 15 9]

值错误:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 4

【问题讨论】:

    标签: python arrays numpy vector format


    【解决方案1】:

    给你:

    import numpy as np
    
    a_multiplier = 3
    b_multiplier = 5
    
    a = np.array([5,32,1,4,3])
    b = np.array([1,5,11,3])
    
    result = np.empty((a.size + b.size,), dtype=a.dtype)
    result[0::2] = a * a_multiplier
    result[1::2] = b * b_multiplier
    

    输出:

    array([15,  5, 96, 25,  3, 55, 12, 15,  9])
    

    【讨论】:

      猜你喜欢
      • 2021-06-10
      • 1970-01-01
      • 2018-10-04
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      相关资源
      最近更新 更多