User Tools

Site Tools


numpy_exercises

1

Q. Given two one dimensional arrays, how to combine them into a 2d numpy array?

A. use np.column_stack((c1, c2))

 % ipython
Python 3.8.5 (default, Sep  4 2020, 07:30:14) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.18.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 
import numpy as np
c1 = np.array([0.39656302, 0.14878788, 0.14948021, 0.26837201, 0.40427337])
c2 = np.array([0.68676044, 0.41183541, 0.72868058, 0.24776482, 0.52792127])
m = np.column_stack((c1, c2))
m
Out[1]: 
array([[0.39656302, 0.68676044],
       [0.14878788, 0.41183541],
       [0.14948021, 0.72868058],
       [0.26837201, 0.24776482],
       [0.40427337, 0.52792127]])

In [2]: 
m.shape
Out[2]: 
(5, 2)

In [3]: 
m.ndim
Out[3]: 
2

You can also get the same result by doing np.vstack((c1, c2)).T . But I like the column_stack() approach as it gives the correct shape right away and does not require a transpose.

In [4]: 
m2 = np.vstack((c1, c2)).T
m2
Out[4]: 
array([[0.39656302, 0.68676044],
       [0.14878788, 0.41183541],
       [0.14948021, 0.72868058],
       [0.26837201, 0.24776482],
       [0.40427337, 0.52792127]])

In [5]: 
np.array_equal(m, m2)
Out[5]: 
True

Ref:-

tags | combine two numpy arrays into 2d array

numpy_exercises.txt · Last modified: 2020/10/25 04:39 by prasanthi