[英]How to reshape a numpy matrix from 2D to 3D column-wise?
我不明白Python中numpy
中的function重塑。我遇到了以下問題:
我想重塑(6, 2)
數組
A = np.c_[np.arange(1, 7), np.arange(6, 12)]
哪個是
array([[ 1, 6],
[ 2, 7],
[ 3, 8],
[ 4, 9],
[ 5, 10],
[ 6, 11]])
進入一個(2, 3, 2)
數組
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 6, 7, 8],
[ 9, 10, 11]]])
我努力了
np.reshape(A, (2, 3, 2), order='F')
但結果不是我想要的。 相反,它是:
array([[[ 1, 6],
[ 3, 8],
[ 5, 10]],
[[ 2, 7],
[ 4, 9],
[ 6, 11]]])
這里有兩個問題:
(2, 2, 3)
,而不是(2, 3, 2)
。order="F"
並不像您認為的那樣。 您真正想要的是使用AT
轉置數組。 此外,您可以使用A.reshape(...)
而不是np.reshape(A, ...)
。
這是代碼:
import numpy as np
A = np.c_[np.arange(1,7), np.arange(6,12)]
print(A)
print("\n->\n")
print(A.T.reshape((2, 2, 3)))
這使:
array([[ 1, 6],
[ 2, 7],
[ 3, 8],
[ 4, 9],
[ 5, 10],
[ 6, 11]])
->
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 6, 7, 8],
[ 9, 10, 11]]])
order="F"
與.T
的解釋嘗試A.ravel(order="F")
以查看數組的元素按"F"
順序排列。 你會得到:
array([[ 1, 6],
[ 2, 7],
[ 3, 8],
[ 4, 9],
[ 5, 10],
[ 6, 11]])
->
array([ 1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11])
現在,如果您在此之后應用正常order
,您將得到預期的結果:
A.ravel(order="F").reshape((2, 2, 3)) ->
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 6, 7, 8],
[ 9, 10, 11]]])
問題是, order="F"
還會影響將拼湊的元素添加回數組的方式。 元素不僅按列取出,它們也按列添加回來。 所以:
[[[], []], [[], []]] ->
[[[1], []], [[], []]] ->
[[[1], []], [[2], []]] ->
[[[1], [3]], [[2], []]] ->
[[[1], [3]], [[2], [4]]] ->
[[[1, 5], [3]], [[2], [4]]] ->
[[[1, 5], [3]], [[2, 6], [4]]] ->
[[[1, 5], [3, 7]], [[2, 6], [4]]] ->
[[[1, 5], [3, 6]], [[2, 6], [4, 7]]] ->
[[[1, 5, 8], [3, 6]], [[2, 6], [4, 7]]] ->
[[[1, 5, 8], [3, 6]], [[2, 6, 9], [4, 7]]] ->
[[[1, 5, 8], [3, 6, 10]], [[2, 6, 9], [4, 7]]] ->
[[[1, 5, 8], [3, 6, 10]], [[2, 6, 9], [4, 7, 11]]]
不是:
[[[1], []], [[], []]] ->
[[[1, 2], []], [[], []]] ->
[[[1, 2, 3], []], [[], []]] ->
[[[1, 2, 3], [4]], [[], []]] ->
[[[1, 2, 3], [4, 5]], [[], []]] ->
[[[1, 2, 3], [4, 5, 6]], [[], []]] ->
[[[1, 2, 3], [4, 5, 6]], [[6], []]] ->
[[[1, 2, 3], [4, 5, 6]], [[6, 7], []]] ->
[[[1, 2, 3], [4, 5, 6]], [[6, 7, 8], []]] ->
[[[1, 2, 3], [4, 5, 6]], [[6, 7, 8], [9]]] ->
[[[1, 2, 3], [4, 5, 6]], [[6, 7, 8], [9, 10]]] ->
[[[1, 2, 3], [4, 5, 6]], [[6, 7, 8], [9, 10, 11]]]
因此,您最終會得到一個奇怪的結果。 如果您只是想用order="F"
取出元素但不想以這種方式將它們添加回去,那么轉置數組將具有相同的效果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.