Create a 2d array of appropriate size. Use a for loop to loop over your 1d array. Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.
You want to reshape
the array.
B = np.reshape(A, (-1, 2))
where -1
infers the size of the new dimension from the size of the input array.
You have two options:
If you no longer want the original shape, the easiest is just to assign a new shape to the array
a.shape = (a.size//ncols, ncols)
You can switch the a.size//ncols
by -1
to compute the proper shape automatically. Make sure that a.shape[0]*a.shape[1]=a.size
, else you'll run into some problem.
You can get a new array with the np.reshape
function, that works mostly like the version presented above
new = np.reshape(a, (-1, ncols))
When it's possible, new
will be just a view of the initial array a
, meaning that the data are shared. In some cases, though, new
array will be acopy instead. Note that np.reshape
also accepts an optional keyword order
that lets you switch from row-major C order to column-major Fortran order. np.reshape
is the function version of the a.reshape
method.
If you can't respect the requirement a.shape[0]*a.shape[1]=a.size
, you're stuck with having to create a new array. You can use the np.resize
function and mixing it with np.reshape
, such as
>>> a =np.arange(9)
>>> np.resize(a, 10).reshape(5,2)
Try something like:
B = np.reshape(A,(-1,ncols))
You'll need to make sure that you can divide the number of elements in your array by ncols
though. You can also play with the order in which the numbers are pulled into B
using the order
keyword.
If your sole purpose is to convert a 1d array X to a 2d array just do:
X = np.reshape(X,(1, X.size))
convert a 1-dimensional array into a 2-dimensional array by adding new axis.
a=np.array([10,20,30,40,50,60])
b=a[:,np.newaxis]--it will convert it to two dimension.
There is a simple way as well, we can use the reshape function in a different way:
A_reshape = A.reshape(No_of_rows, No_of_columns)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With