python - 在 python numpy 中重塑矩阵
问题描述
我有以下矩阵:
x = np.array([["a","b","c","d"], ["e","f","g","h"], ["i","j","k","l"], ["m","n","o","p"]])
[['a' 'b' 'c' 'd']
['e' 'f' 'g' 'h']
['i' 'j' 'k' 'l']
['m' 'n' 'o' 'p']]
我如何重塑:
[['a' 'b' 'e' 'f']
['c' 'd' 'g' 'h']
['i' 'j' 'm' 'n']
['k' 'l' 'o' 'p']]
它试过了
np.array([x.reshape(2,2) for x in x]).reshape(4,4)
但它只是给了我原来的矩阵。
解决方案
您可以使用numpy.lib.stride_tricks.as_strided
:
from numpy.lib.stride_tricks import as_strided
x = np.array([["a","b","c","d"], ["e","f","g","h"], ["i","j","k","l"], ["m","n","o","p"]])
y = as_strided(x, shape=(2, 2, 2, 2),
strides=(8*x.itemsize, 2*x.itemsize, 4*x.itemsize,x.itemsize)
).reshape(x.shape).copy()
print(y)
印刷:
array([['a', 'b', 'e', 'f'],
['c', 'd', 'g', 'h'],
['i', 'j', 'm', 'n'],
['k', 'l', 'o', 'p']], dtype='<U1')
我们可以将as_strided
原始数组变成一个包含 42x2
个块的数组:
>>> as_strided(x, shape=(2, 2, 2, 2),
strides=(8*x.itemsize, 2*x.itemsize, 4*x.itemsize,x.itemsize)
)
array([[[['a', 'b'],
['e', 'f']],
[['c', 'd'],
['g', 'h']]],
[[['i', 'j'],
['m', 'n']],
[['k', 'l'],
['o', 'p']]]], dtype='<U1')
您可以在此处as_strided
详细了解更多信息
推荐阅读
- react-native - clojurescript react-native 项目中使用 re-natal 的“未知命名模块 xmlhttprequest”
- vba - 多列组合框的不在列表中事件导致添加新条目时移动到下一条记录
- reduction - 当L2是NP完全时,L1可以简化为L2
- python - 计算预测误差时的巨大数字
- python - 将参数传递给嵌套函数如何在 python 的后台工作?
- docker - 如何安全地将可能包含特殊字符的变量传递给 Ansible 中的 docker-compose 文件
- c# - Razor 页面中的 Asp.net 核心本地化
- android - Android中的Javacv人脸识别:dlopen失败:找不到库libopencv_legacy.so
- sql - 查询以列出 IBM DB2 中的所有可用数据库
- reactjs - Reparent 组件如何反应并保持组件实例及其状态