【问题标题】:How I can add column to matrix in numpy [duplicate]如何在 numpy 中向矩阵添加列 [重复]
【发布时间】:2020-08-19 20:52:13
【问题描述】:

我想在 0 索引处将一列添加到 5x5 矩阵。 np.append() 正在工作,但我搜索另一种方式。

import numpy as np
arr = np.array(range(25)).reshape(5,5)
ones = np.ones((arr.shape[0],1))
arr_with_ones = np.append(ones, arr, axis=1)
print(arr_with_ones)

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您无需预定义ones 数组。可以直接使用numpy.insert函数:

    arr = np.array(range(25)).reshape(5,5)
    arr_with_ones = np.insert(arr, 0, 1, axis=1)
    

    np.insert(arr, 0, 1, axis=1) 在数组arraxis=1(二维数组中的列)的索引0 中插入value=1

    输出:

    [[ 1  0  1  2  3  4]
     [ 1  5  6  7  8  9]
     [ 1 10 11 12 13 14]
     [ 1 15 16 17 18 19]
     [ 1 20 21 22 23 24]]
    

    【讨论】:

      【解决方案2】:

      你可以这样试试:

      import numpy as np
      arr = np.array(range(25)).reshape(5,5)
      ones = np.ones((arr.shape[0],1))
      arr_with_ones = np.c_[ones, arr]
      

      【讨论】:

        【解决方案3】:

        您也可以尝试np.hstack((ones,arr)) 功能。

        【讨论】:

          猜你喜欢
          • 2017-04-04
          • 2013-02-20
          • 2013-03-22
          • 2012-08-11
          • 1970-01-01
          • 2014-03-01
          • 1970-01-01
          相关资源
          最近更新 更多