python - 如何将 NumPy (k,n,m)-size ndarray 转换为 (k)-size dttype=object ndarray of (n,m)-size ndarrays?
问题描述
我有一个 int 大小 (k,n,m) 的 NumPy ndarray A,表示每个大小为 nxm 像素的 k 个图像。我想将其转换为大小为 (k,) 的 dtype=object ndarray B,其中包含每个单独的图像作为大小 (n,m) 的 ndarray。
我可以使用 for 循环(如下)来做到这一点,但是有没有更优雅/直接的方式?
A = np.arange(2*3*4).reshape(2,3,4)
B = np.empty(A.shape[0],dtype=object)
for i in range(0,A.shape[0]):
B[i] = A[i]
print(B)
array([array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]), array([[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])], dtype=object)
解决方案
你的数组:
In [37]: A = np.arange(2*3*4).reshape(2,3,4)
...:
...: B = np.empty(A.shape[0],dtype=object)
...: for i in range(0,A.shape[0]):
...: B[i] = A[i]
...:
In [38]: B
Out[38]:
array([array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]), array([[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])], dtype=object)
A
分配给的替代方式B
。更短,但不一定更快。
In [39]: B[:]=list(A)
In [40]: B
Out[40]:
array([array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]), array([[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])], dtype=object)
直接分配不起作用;它必须是数组列表,而不是数组:
In [41]: B[:]=A
Traceback (most recent call last):
File "<ipython-input-41-b3ca91787565>", line 1, in <module>
B[:]=A
ValueError: could not broadcast input array from shape (2,3,4) into shape (2,)
另一个答案不起作用:
In [42]: np.array([*A], dtype=object)
Out[42]:
array([[[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]], dtype=object)
推荐阅读
- javascript - 如何修复无法解析模块 REACT-NATIVE
- reactjs - 如何检查我的复选框是否被选中。将其保存到 LocalStorage
- html - 如何在 HTML 中向网站添加“退出按钮”?
- javascript - 使用 Google Script,如何使用 Macaroon 连接到 API
- python - 熊猫填充和滚动平均值
- django-forms - 我在安装 django cripsy forms 时遇到错误
- javascript - TypeError: navigator.getUserMedia 不是函数
- python - 使用 Selenium 引用页面上的某个元素时遇到问题
- dynamic - Camel Dynamic To(又名 ToD)是否仍然需要明确?
- javascript - 我在处理外部文件时遇到问题 | 不和谐.js