Reputation: 137
As input for a code, I need a 'ndarray' (call it C), whose shape is: ((4,N),(4,N)). So, if N=3, I thought that I can construct it in this way:
import numpy as np
A=np.array([[1, 2,3], [0.1, 0.2,0.3],[0.4,0.5,0.6],[0.7,0.8,0.9]])
B=np.array([[4,5,6], [0.4, 0.5,0.6],[0.7,0.8,0.9],[0.7,0.8,1]])
Therefore, how can I combine A and B to get C, whose shape is ((4,3),(4,3)) (s.t. C[0] should also be A, and C[1] should be B)?
I tried:
C=np.concatenate(([A], [B]), axis=0)
, but resulting C.shape was (2, 4, 3) instead of ((4,3),(4,3)). I naively tried then to reshape C:
C.reshape((4,3),(4,3))
but then I get an error message.
I am sorry if the question is too basic, I have just started using python.
Best,
Steven
Upvotes: 0
Views: 68
Reputation: 96
In order to do what you're asking, it is simpler if you understand how the numpy ndarrays work. In the example you are listing, you can make an array of exactly that type in 3 dimensions with the following shape:
numpy.zeros((4,N,2));
This would create an array with the shape you're asking for. The documentation page on numpy array creation has a lot of great information on how to use it.
However, if you want to merge two arrays, there are many ways to do it.
stacked0=numpy.stack(A,B) # Stack the arrays along a new axis (a 3rd axis in this case)
stacked0.shape # outputs (2,4,3) in the example arrays.
This created a new axis and merged along it, in this case, the default replaces the first axis (axis=0), and shifts the remaining axes down. This only matters for when you need to index it later and some persnickety performance in advanced applications. The most important thing as a beginner is to understand which axis you want to merge along.
stacked1=numpy.stack([A,B],axis=1) # Replaces the second axis to stack
stacked1.shape # (4,2,3)
stacked2=numpy.stack([A,B],axis=2) # Appends a third axis
stacked2.shape # (4,3,2)
You can also concatenate them along existing axes.
concated0 = numpy.concatenate([A,B],axis=0) # merges them along the first axis
concated0.shape # (8,3)
concated1 = numpy.concatenate([A,B],axis=1)
concated1.shape # (4,6)
See the array manimpulations docs for more options on how to rearrange your arrays.
Upvotes: 1