gpt4 book ai didi

python - Numpy:二维数组的 reshape

转载 作者:行者123 更新时间:2023-12-03 23:42:10 25 4
gpt4 key购买 nike

给定以下形状的输入 numpy 数组 (n**2 * m, m) , 与 n=2m=5 :

A = np.array([[  71.87,   47.8 ,   24.84,   25.31,   15.43],
[ 174.8 , 131.84, 57.57, 76.53, 48.5 ],
[ 4.4 , 2. , 1.6 , 1. , 0. ],
[ 28.71, 15. , 10.5 , 4.17, 2.52],
[ 222.8 , 123.59, 7.72, -39.33, 4.65],
[ 156.84, 138.17, 21.75, 80.86, 44.55],
[ 89.5 , 133.01, -114.69, 1. , -167.7 ],
[ 21.25, 19.57, -177.65, 57.38, -119.75],
[ 162.33, 7.72, -51.72, 117.31, -87.87],
[ 77.57, 26.75, 36.64, 6.99, 25.97],
[ 276.6 , 275.31, -128.61, 105.7 , -86.5 ],
[ 135.5 , 232.67, 9.15, -5.25, -48.62],
[ 325.31, 238.17, -32.69, 41.55, 3.32],
[ 126.53, 118.36, -13.64, 104.64, 7.66],
[ 522.25, 176. , -338.05, 265.95, -411.87],
[ 16.67, 116.75, -255.25, 109.61, -397.18],
[ 15.43, 267.15, 159.63, 3.32, 30.31],
[ 48.5 , 83.93, 63.47, 17.66, 70.16],
[ 321.25, 213.55, 1. , 368.13, -261.55],
[ 107.52, 5.25, -89.25, 423.44, -80.89]])
如何 reshape 和置换 A 的轴为了获得以下输出 B形状 (n*m, n*m) ?
B = np.array([[  71.87,  174.8 ,  222.8 ,  156.84,  162.33,   77.57,  325.31,  126.53,   15.43,   48.5 ],
[ 4.4 , 28.71, 89.5 , 21.25, 276.6 , 135.5 , 522.25, 16.67, 321.25, 107.52],
[ 47.8 , 131.84, 123.59, 138.17, 7.72, 26.75, 238.17, 118.36, 267.15, 83.93],
[ 2. , 15. , 133.01, 19.57, 275.31, 232.67, 176. , 116.75, 213.55, 5.25],
[ 24.84, 57.57, 7.72, 21.75, -51.72, 36.64, -32.69, -13.64, 159.63, 63.47],
[ 1.6 , 10.5 , -114.69, -177.65, -128.61, 9.15, -338.05, -255.25, 1. , -89.25],
[ 25.31, 76.53, -39.33, 80.86, 117.31, 6.99, 41.55, 104.64, 3.32, 17.66],
[ 1. , 4.17, 1. , 57.38, 105.7 , -5.25, 265.95, 109.61, 368.13, 423.44],
[ 15.43, 48.5 , 4.65, 44.55, -87.87, 25.97, 3.32, 7.66, 30.31, 70.16],
[ 0. , 2.52, -167.7 , -119.75, -86.5 , -48.62, -411.87, -397.18, -261.55, -80.89]])
使用 for 可以轻松完成此转换循环,但由于我需要在这里高效,我正在寻找合适的 reshape -基于解决方案,对其背后的逻辑进行了一些澄清。
任何帮助将不胜感激。

最佳答案

仔细观察您的数据才发现,在输出中,A 的列已被 n*n 块分块并平铺成 n x n正方形。例如,B[:2, :2]具有 A[:4, 0] 的值.
因此,关键是尝试将这些块放入连续的维度中,然后在最终 reshape 之前使用适当轴的转置。
长话短说:

B = np.reshape(np.reshape(A.T, (m, m, n, n)).transpose(0, 2, 1, 3), (n*m, n*m))

关于python - Numpy:二维数组的 reshape ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65134737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com