Aashish sharma Sharma
Aashish sharma Sharma

Reputation: 307

slicing column in numpy array and creating new matrix

I have to concatenate columns of numpy matrix to create new matrix. I have 2 codes. One is working fine. Other is giving me trouble. The one working fine is

x = np.array(range(24))
x = x.reshape((3,4,2))
y = np.array(range(100,124))
y = y.reshape((3,4,2))
z = np.concatenate((x,y))

Now result is 6,4,2 if axis =0 it si 3,8,2 if axis=1 and 3,4,4 if axis=2. But look at another code:

a=np.array(([1,2,3],[4,5,6],[7,8,9])
b=a[:,1] # took one column
c=a[:,0] # again took 1 column
d=np.concatenate((b,c))

If I provide axis=0 result is 1x6. If I provide axis=1 it is again 1,6. I want in 1 case 1,6 in another 3,2. ie

[2,1],[5,4],[8,7]

and in another 2,3 ie

[2,5,8],[1,4,7]

I am wondering why concatenate is not working for me?

Upvotes: 0

Views: 134

Answers (1)

sinhayash
sinhayash

Reputation: 2803

Use vstack

>>> import numpy as np
>>> a=np.array(([1,2,3],[4,5,6],[7,8,9]))
>>> b=a[:,1] # took one column
>>> c=a[:,0] # again took 1 column
>>> np.vstack((b,c))
array([[2, 5, 8],
       [1, 4, 7]])

Use np.transpose if necessary

Upvotes: 1

Related Questions