Convert a 1D array to a 2D array in numpy
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.
Numpy reshape 1d to 2d array with 1 column
You could do -
ar.reshape(ar.shape[0],-1)
That second input to reshape
: -1
takes care of the number of elements for the second axis. Thus, for a 2D
input case, it does no change. For a 1D
input case, it creates a 2D
array with all elements being "pushed" to the first axis because of ar.shape[0]
, which was the total number of elements.
Sample runs
1D Case :
In [87]: ar
Out[87]: array([ 0.80203158, 0.25762844, 0.67039516, 0.31021513, 0.80701097])
In [88]: ar.reshape(ar.shape[0],-1)
Out[88]:
array([[ 0.80203158],
[ 0.25762844],
[ 0.67039516],
[ 0.31021513],
[ 0.80701097]])
2D Case :
In [82]: ar
Out[82]:
array([[ 0.37684126, 0.16973899, 0.82157815, 0.38958523],
[ 0.39728524, 0.03952238, 0.04153052, 0.82009233],
[ 0.38748174, 0.51377738, 0.40365096, 0.74823535]])
In [83]: ar.reshape(ar.shape[0],-1)
Out[83]:
array([[ 0.37684126, 0.16973899, 0.82157815, 0.38958523],
[ 0.39728524, 0.03952238, 0.04153052, 0.82009233],
[ 0.38748174, 0.51377738, 0.40365096, 0.74823535]])
Numpy: get 1D array as 2D array without reshape
Check the code of hstack
and vstack
. One, or both of those, pass the arguments through atleast_nd
. That is a perfectly acceptable way of reshaping an array.
Some other ways:
arr = np.array([1,2,3,4,5]).reshape(-1,1) # saves the use of len()
arr = np.array([1,2,3,4,5])[:,None] # adds a new dim at end
np.array([1,2,3],ndmin=2).T # used by column_stack
hstack
and vstack
transform their inputs with:
arrs = [atleast_1d(_m) for _m in tup]
[atleast_2d(_m) for _m in tup]
test data:
a1=np.arange(2)
a2=np.arange(10).reshape(2,5)
a3=np.arange(8).reshape(2,4)
np.hstack([a1.reshape(-1,1),a2,a3])
np.hstack([a1[:,None],a2,a3])
np.column_stack([a1,a2,a3])
result:
array([[0, 0, 1, 2, 3, 4, 0, 1, 2, 3],
[1, 5, 6, 7, 8, 9, 4, 5, 6, 7]])
If you don't know ahead of time which arrays are 1d, then column_stack
is easiest to use. The others require a little function that tests for dimensionality before applying the reshaping.
Numpy: use reshape or newaxis to add dimensions
How to transform 1D Array to 2D Array with duplication
With numpy.tile
.
>>> a = np.arange(5)
>>> np.tile(a, (3, 1))
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Convert 1D array with coordinates into 2D array in numpy
With np.bincount
-
def accumulate_arr(coords, arr):
# Get output array shape
m,n = coords.max(1)+1
# Get linear indices to be used as IDs with bincount
lidx = np.ravel_multi_index(coords, (m,n))
# Or lidx = coords[0]*(coords[1].max()+1) + coords[1]
# Accumulate arr with IDs from lidx
return np.bincount(lidx,arr,minlength=m*n).reshape(m,n)
Sample run -
In [58]: arr
Out[58]: array([1, 2, 3, 4])
In [59]: coords
Out[59]:
array([[0, 0, 1, 2],
[0, 0, 2, 2]])
In [60]: accumulate_arr(coords, arr)
Out[60]:
array([[3., 0., 0.],
[0., 0., 3.],
[0., 0., 4.]])
Another with np.add.at
on similar lines and might be easier to follow -
def accumulate_arr_v2(coords, arr):
m,n = coords.max(1)+1
out = np.zeros((m,n), dtype=arr.dtype)
np.add.at(out, tuple(coords), arr)
return out
Merging 1D arrays into a 2D array
Take into consideration scalability. If we increase the size of the arrays, complete numpy solutions are quite faster than solutions involving python built-in operations:
np.random.seed(1234)
X = np.random.rand(10000)
y = np.random.rand(10000)
%timeit np.array(list(map(lambda i: [X[i],y[i]], range(len(X)))))
6.64 ms ± 32.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.array(list(zip(X, y)))
4.53 ms ± 33.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.column_stack((X,y))
19.2 µs ± 30.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.transpose([X,y])
16.2 µs ± 247 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.vstack((X, y)).T
14.2 µs ± 94.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Taking into account all proposed solutions, np.vstack(X,y).T
is the fastest when working with greater array sizes.
Transposing a 1D NumPy array
It's working exactly as it's supposed to. The transpose of a 1D array is still a 1D array! (If you're used to matlab, it fundamentally doesn't have a concept of a 1D array. Matlab's "1D" arrays are 2D.)
If you want to turn your 1D vector into a 2D array and then transpose it, just slice it with np.newaxis
(or None
, they're the same, newaxis
is just more readable).
import numpy as np
a = np.array([5,4])[np.newaxis]
print(a)
print(a.T)
Generally speaking though, you don't ever need to worry about this. Adding the extra dimension is usually not what you want, if you're just doing it out of habit. Numpy will automatically broadcast a 1D array when doing various calculations. There's usually no need to distinguish between a row vector and a column vector (neither of which are vectors. They're both 2D!) when you just want a vector.
Transfering 1d array into 2d array without numpy
As far as I understand you need to convert a 1d array into a 2d array. You can do it either using a while loop, for loop or list comprehension.
using a while loop:
fixedarr = []
name = str(input("Name : "))
i=0
name_len = len(name) # name lenght
while i < name_len:
fixedarr.append([name[i:i+4]])
i += 4
using for loop:
for i in range(0, len(name), 4):
fixedarr.append(name[i:i+4])
using list comprehension:
fixedarr = [name[i:i+4] for i in range(0, len(name), 4)]
Related Topics
How to Access a Standard-Library Module in Python When There Is a Local Module with the Same Name
How to Combine Python Asyncio with Threads
Py_Initialize/Py_Finalize Not Working Twice with Numpy
How to Create an SQL View with SQLalchemy
How to Specify "Nullable" Return Type with Type Hints
Type Hints with User Defined Classes
Pyspark: Explode JSON in Column to Multiple Columns
Predict Classes or Class Probabilities
Python: Read Lines from Compressed Text Files
Find Substring in String But Only If Whole Words
How to Use Valgrind with Python
Which Seeds Have to Be Set Where to Realize 100% Reproducibility of Training Results in Tensorflow
Plot a Bar Using Matplotlib Using a Dictionary
Why Is the Empty Dictionary a Dangerous Default Value in Python