如何在python中合并2列 [英] How can I merge 2 column in python

查看:114
本文介绍了如何在python中合并2列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经使用numpy定义了一个2x2矩阵:

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

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

现在使用其他2x1矩阵:

Now the other 2x1 matrix:

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

如何将这2个矩阵按列连接起来,这样它将变成:

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]])

推荐答案

有一个numpy.concatenate 或仅使用hstackvstack

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.

要删除第i列,您可​​以将子数组带到该列,并从下一个开始,并将它们连接起来.例如,要删除第二列(索引1):

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])

一般来说

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

然后

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

实际上,正如评论中指出的那样-numpy实现了自己的delete方法

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

np.delete(a, 1, 1)

已删除第二列

并删除多个可以使用

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

第三个参数是轴说明符,0表示行,1列,None表示整个数组

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

这篇关于如何在python中合并2列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆