首页 > 解决方案 > 如何在 numpy 中向矩阵添加列

问题描述

我想在 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)

标签: pythonnumpy

解决方案


您不需要预定义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)沿数组value=1的索引插入(即二维数组中的列)。0axis=1arr

输出:

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

推荐阅读