Python中如何按特定方式拼接两个numpy数组?
a and b in NumPy Hey there! Let's work through how to get that exact array structure you're aiming for with NumPy. It makes sense that functions like stack, hstack, or concatenate might not have given you the right result—those are designed to merge arrays entirely along an axis, while you need to pair individual elements from a and b at each position.
Let's Break Down the Problem
Your arrays have these shapes:
a: shape(7, 1)(7 rows, 1 column)b: shape(7, 3)(7 rows, 3 columns)
You want to take each row from a and pair it with the same-indexed row from b, creating a new array where each element is a pair like [[0], [1,2,3]].
Solution 1: Intuitive List Comprehension (Great for Beginners)
If you prefer something easy to read, a list comprehension lets you explicitly loop through each index and pair the elements:
import numpy as np # Define your arrays a = np.array([[0], [1], [2], [3], [4], [5], [6]]) b = np.array([[1,2,3], [1,2,3], [1,2,3], [1,2,3], [1,2,3], [1,2,3], [1,2,3]]) # Create the paired array c = np.array([[a[i], b[i]] for i in range(a.shape[0])]) # If you want a pure Python list (matching your exact expected output), use .tolist() c_list = c.tolist() print(c_list) # Output: [[[0], [1, 2, 3]], [[1], [1, 2, 3]], ..., [[6], [1, 2, 3]]]
Solution 2: Efficient NumPy stack (Better for Large Data)
For a more "NumPy-native" approach, use np.stack() with axis=1. This stacks a and b along a new axis, effectively pairing their rows directly:
import numpy as np a = np.array([[0], [1], [2], [3], [4], [5], [6]]) b = np.array([[1,2,3]] * 7) c = np.stack([a, b], axis=1) print(c.tolist()) # Converts to the list structure you want
Why Your Previous Attempts Didn't Work
hstack/concatenate(axis=1): Merges all columns ofaandbinto a single(7, 4)array, not paired elements.vstack: Throws an error because the number of columns inaandbdon't match.- Basic
stack(axis=0): Stacks the arrays vertically, which isn't what you need here.
Hope this clears things up and gives you exactly the result you're looking for!
内容的提问来源于stack exchange,提问作者DJosh

