【问题标题】:Inserting a column at specific location in 2D array in numpy?在numpy的二维数组中的特定位置插入一列?
【发布时间】:2017-04-11 02:11:57
【问题描述】:

我有一个 2D numpy 数组,我需要在第一列之前添加一列作为 id。

我的数组是这样的:

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

我要添加的列是y = ['1' '2' '3' '4' '5']

而目标输出是:

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

有什么办法可以做到吗? (我可以找到插入行而不是列的解决方案)

【问题讨论】:

    标签: python arrays numpy insertion


    【解决方案1】:

    定义您的新列:

    col = np.array(['1','2','3','4','5'])
    col.shape = (5,1)
    

    并在开头插入:

    target = np.hstack((col, x))
    

    对于在任何给定位置插入i,您可以这样做:

    target = np.hstack((x[:,:i], col, x[:,i:]))
    

    但在我看来,使用 pandas 数据框而不是 numpy 数组会是更好的选择...

    【讨论】:

    • 另外,np.concatenate((col, x), axis = 1)
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2016-08-16
    • 2021-02-06
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    相关资源
    最近更新 更多