如何将Numpy数组x1与x2组合为形状(10,37632,4)的数组x3?
Got it, let's break this down! The core issue here is that you need to add new dimensions to your arrays first so they can align correctly using NumPy's broadcasting rules—your earlier attempts like append or hstack only work along existing axes, which is why you ended up with a 2D array instead of the 3D shape you want.
Why Your Previous Tries Didn't Work
When you used np.append(x1, x2, axis=1), you were just sticking the 4 columns of x2 onto the end of x1's 37632 columns. That merges them into a single 2D array (shape (10, 37636)), but you need to create a new third dimension instead of expanding an existing one.
The Solution: Expand Dimensions + Broadcasting
To get the (10, 37632, 4) shape while preserving all original data, we'll expand each array with a singleton dimension (size 1) so NumPy can automatically "stretch" them to match each other's shape. Here's how:
import numpy as np # Replace with your actual non-zero data x1 = np.random.rand(10, 37632) x2 = np.random.rand(10, 4) # Add a third dimension to x1: shape becomes (10, 37632, 1) x1_expanded = np.expand_dims(x1, axis=2) # Add a second dimension to x2: shape becomes (10, 1, 4) x2_expanded = np.expand_dims(x2, axis=1) # Now combine them using broadcasting # Option 1: If you want each position (i,j,k) to be x1[i,j] paired with x2[i,k] (e.g., multiplied) x3 = x1_expanded * x2_expanded # Option 2: If you just want to repeat x1 across all 4 columns and x2 across all 37632 rows # x3 = x1_expanded + x2_expanded # This adds x2's values to every x1 element in the same sample
How This Works
np.expand_dims(x1, axis=2)turns your 2Dx1into a 3D array where each of the 37632 elements has its own single-element third dimension.np.expand_dims(x2, axis=1)turnsx2into a 3D array where each of the 4 elements has its own single-element second dimension.- NumPy's broadcasting rules automatically stretch these singleton dimensions to match each other:
x1_expandedgets stretched along the third axis to fit 4 elements.x2_expandedgets stretched along the second axis to fit 37632 elements.
- The result is a
(10, 37632, 4)array where all original data fromx1andx2is preserved (either through pairing operations like multiplication, or repeated across the new dimension).
If You Need Separate Channels
If you actually want to keep x1 and x2 as distinct channels (instead of combining their values), you'd need a shape like (10, 37632, 5) (1 channel for x1, 4 for x2). To do that, you'd use np.concatenate after expanding x1 to (10, 37632, 1):
x3_combined_channels = np.concatenate([x1_expanded, x2_expanded], axis=2)
内容的提问来源于stack exchange,提问作者mike g

