Home > other >  Error while appending to columns (to ndarray)
Error while appending to columns (to ndarray)

Time:11-07

I have ndarray of shape:

(20640, 7)

I'm trying to add new columns:

np.append(x, [m[:,0], m[:,1]], axis = 1)

where:

m[:,0].shape = m[:,1].shape = (20640,)

And I'm getting error:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 20640 and the array at index 1 has size 2

simple example to get this error: import numpy as np

x = np.ones((20640, 7))
m = np.ones((20640, 2))
np.append(x, [m[:,0], m[:,1]], axis = 1)

How can I add those 2 columns ?

CodePudding user response:

If you just want to concatenate x and m[:,0]/m[:,1] as columns, use np.c_:

np.c_[x, m[:,0], m[:,1]]

Example:

x = np.zeros((20640, 7))
m = np.ones((20640, 2))
np.c_[x, m[:,0], m[:,1]]

output:

array([[0., 0., 0., ..., 0., 1., 1.],
       [0., 0., 0., ..., 0., 1., 1.],
       [0., 0., 0., ..., 0., 1., 1.],
       ...,
       [0., 0., 0., ..., 0., 1., 1.],
       [0., 0., 0., ..., 0., 1., 1.],
       [0., 0., 0., ..., 0., 1., 1.]])
  • Related