如何优雅地交错合并NumPy数组?现有实现可优化吗?
Great question! You're right that manually listing each row isn't scalable or elegant—here are three cleaner, more efficient approaches to achieve your desired interleaved array:
Method 1: List Comprehension + Concatenate (Readable & Scalable)
This approach builds small pairs of [x, row] for each row in y, then concatenates them all together. It’s easy to read and works for any number of rows in y:
import numpy as np x = np.array([1,2,3,4,5]) y = np.array([[4,6,2,6,9], [5,9,8,7,4], [3,2,5,4,9]]) result = np.concatenate([[x], row] for row in y)
Method 2: Slice Assignment (Most Efficient)
Preallocate an empty array of the correct shape, then use slice indexing to fill in x and y rows in one go. This is ideal for large datasets since it avoids extra intermediate arrays:
result = np.empty((2 * len(y), x.size), dtype=x.dtype) result[::2] = x # Fill even-indexed rows (0,2,4) with x result[1::2] = y # Fill odd-indexed rows (1,3,5) with y's rows
Method 3: Tile + Stack + Reshape (Vectorized Operation)
Repeat x to match the number of rows in y, stack it with y along a new axis, then reshape to flatten the pairs into rows:
repeated_x = np.tile(x, (len(y), 1)) # Shape: (3,5) combined = np.stack([repeated_x, y], axis=1) # Shape: (3,2,5) result = combined.reshape(-1, x.size) # Shape: (6,5)
All three methods will produce your desired output:
array([[1, 2, 3, 4, 5], [4, 6, 2, 6, 9], [1, 2, 3, 4, 5], [5, 9, 8, 7, 4], [1, 2, 3, 4, 5], [3, 2, 5, 4, 9]])
Content of the question来源于stack exchange,提问作者mocs
相关产品推荐
相关产品推荐

