簡體   English   中英

重新排列具有不同長度的 2 個數組以創建第三個數組 Numpy Python

[英]Rearranging 2 arrays with different lengths to create a third array Numpy Python

我在ab下方有 2 個數組組合來生成result a乘以a_multiplierb乘以b_multiplier ab有不同長度的數組,我想將它們組合和相乘,然后按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

干得好:

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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM