python - 如何在 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)
解决方案
您不需要预定义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
的索引插入(即二维数组中的列)。0
axis=1
arr
输出:
[[ 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]]
推荐阅读
- reactjs - 使用自定义组件传递带有 onChange 事件的附加参数
- google-chrome - 扩展程序可以在 kiosk 模式下在 Chrome OS 上运行吗?
- django - heroku 上的 django:celery worker 在访问 s3 媒体以读取和处理媒体文件时被禁止 403
- asp.net-core - 我应该在每个页面上还是在 Layout.cshtml 部分文件中放置一个脚本部分?
- node.js - 修改 npm 模块文件夹外的 npm 包
- c# - 如何在 C# 中从 RSA 私钥和颁发者生成授权令牌?
- html - 如何访问跨度值
- javascript - 非变异数组
- azure-application-insights - 无法在 Azure App Insights 中设置警报
- r - 如何根据 R 中的字符串模式列表对列进行分组?