[英]Inserting a column at specific location in 2D array in numpy?
I have a 2D numpy array and I need to add one column before the first column as id. 我有一个二维的numpy数组,我需要在第一列之前添加一个列作为id。
My array is this: 我的数组是这样的:
x = [['8' '4' 'M' '55' '7' 'S' '7' '2']
['36' '4' 'F' '58' '1' 'M' '7' '7']
['33' '3' 'M' '34' '4' 'M' '2' '3']
['43' '1' 'F' '64' '4' 'M' '7' '68']
['1' '2' 'M' '87' '4' 'M' '7' '1']]
The column that I want to add is this y = ['1' '2' '3' '4' '5']
我要添加的列是
y = ['1' '2' '3' '4' '5']
And the target output is: 目标输出为:
z = [['1' '8' '4' 'M' '55' '7' 'S' '7' '2']
['2' '36' '4' 'F' '58' '1' 'M' '7' '7']
['3' '33' '3' 'M' '34' '4' 'M' '2' '3']
['4' '43' '1' 'F' '64' '4' 'M' '7' '68']
['5' '1' '2' 'M' '87' '4' 'M' '7' '1']]
Is there any way that I can do it? 有什么办法可以做到吗? (I can find a solution for inserting a row, but not a column)
(我可以找到一种插入行而不插入列的解决方案)
define your new column: 定义新列:
col = np.array(['1','2','3','4','5'])
col.shape = (5,1)
and insert it at the start: 并将其插入开头:
target = np.hstack((col, x))
for inserting at any given position i
, you can do it like this: 要在任何给定位置
i
插入,您可以这样做:
target = np.hstack((x[:,:i], col, x[:,i:]))
But it looks to me like using a pandas dataframe rather than a numpy array would be a better option... 但是在我看来,使用pandas数据框而不是numpy数组将是更好的选择...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.