Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge 2 column in python

Tags:

python

numpy

Suppose that I have define one 2x2 matrix using numpy:

array([[1, 2],
       [2, 3]]) 

Now the other 2x1 matrix:

array([[3],
       [4]])

How can I concatenate these 2 matrix by column, so that it will become:

array([[1, 2, 3],
       [2, 3, 4]])

And how can I also delete the specify column, so that it will became

array([[1],
       [2]])
like image 573
liumilan Avatar asked Dec 26 '22 20:12

liumilan


2 Answers

There is a numpy.concatenate method

import numpy as np
np.concatenate( [ np.array( [ [1,2], [2,3] ] ), np.array( [ [3],[4] ] ) ] , axis = 1)

or simply use hstack or vstack

np.hstack( [ np.array( [ [1,2], [2,3] ] ), np.array( [ [3],[4] ] ) ] )

These can be also used to remove the column (concatenate two subarrays) - this can be used to remove many columns.

To remove i'th column you can take subarrays to this column, and from the next one, and concatenate them. For example, to remove second column (index 1):

a - np.array( [ [1,2,3], [2,3,4] ] )
a1= a[:,:1]
a2= a[:,2:]
np.hstack([a1,a2])

so in general

def remove_column( a, i ):
    return np.hstack( [a[:,:i], a[:,(i+1):] ] )

and then

>>> remove_column(a, 1)
array([[1, 3],
       [2, 4]])
>>> remove_column(a, 0)
array([[2, 3],
       [3, 4]])

Actually, as pointed out in the comment - numpy implements its own delete method

np.delete(a, 1, 1)

deleted second column

and deleting multiple ones can be performed using

np.delete(a, [column1, columne2, ..., columnK], 1)

The third argument is the axis specifier, 0 would imply rows, 1 columns, None flatterns the whole array

like image 116
lejlot Avatar answered Dec 28 '22 09:12

lejlot


You can use numpy.hstack:

>>> import numpy as np
>>> a = np.array([[1,2], [2,3]])
>>> b = np.array([[3], [4]])
>>> np.hstack((a,b))
 array([[1, 2, 3],
        [2, 3, 4]])

Removing is even easier, just slice:

>>> c = a[:,:1]
 array([[1],
        [2]])
like image 42
jabaldonedo Avatar answered Dec 28 '22 10:12

jabaldonedo