python - 如何为 numpy 元素添加维度?
问题描述
我有一个像这样的 numpy.array
[[1,2,3]
[4,5,6]
[7,8,9]]
我怎样才能将其更改为:-
[[[1,0], [2,0], [3,0]]
[[4,0], [5,0], [6,0]]
[[7,0], [8,0], [9,0]]]
提前致谢。
解决方案
作为a
输入数组,您可以使用array-assignment
这将适用于通用n-dim
输入 -
out = np.zeros(a.shape+(2,),dtype=a.dtype)
out[...,0] = a
样品运行 -
In [81]: a
Out[81]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [82]: out = np.zeros(a.shape+(2,),dtype=a.dtype)
...: out[...,0] = a
In [83]: out
Out[83]:
array([[[1, 0],
[2, 0],
[3, 0]],
[[4, 0],
[5, 0],
[6, 0]],
[[7, 0],
[8, 0],
[9, 0]]])
如果你玩broadcasting
,这里有一个紧凑的 -
a[...,None]*[1,0]
推荐阅读
- r - 在循环中在数据表中写入值的最快方法?
- r - 我想根据单独的反应表中的多项选择来过滤新数据集
- excel - 如何使用 vbscript 从数据库中提取数据到不同的 Excel 工作表?
- c# - 保存PNG时未保存颜色通道
- visual-studio-code - 如何更改 VS Code 中括号的颜色?
- javascript - 对 jquery 选择器感到困惑
- postgresql - 如何在 Postgresql 脚本中存储常量值
- python - Python计算器代码没有正确除法和乘法
- python - Python从字典内的列表中获取值
- html - 如何为响应式窄显示器定义 DIV 堆栈排序