解疑 Numpy 中的 transpose

2021-07-31 16:15:18 字數 3020 閱讀 7632

# 官方文件描述

numpy.ndarray.transpose

ndarray.transpose(*axes)

returns a view of

the array with axes transposed.

for a

1-d array, this has no effect. (to change between column and row vectors, first cast the

1-d array into

a matrix object.) # transpose 對一維陣列無效

for a

2-d array, this is the usual matrix transpose. for an n-d array, if axes are given, their order indicates how the axes are permuted (see examples). if axes are not provided and

a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then

a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).

# 對二維陣列,其實就相當於矩陣的轉置

parameters:

axes : none, tuple of ints, or n ints

none or no argument: reverses the order of

the axes.

tuple of ints: i in

the j-th place in

the tuple means a『s i-th axis becomes a.transpose()『s j-th axis.

n ints: same as

an n-tuple of

the same ints (this form is intended simply as

a 「convenience」 alternative to

the tuple form)

returns:

out : ndarray

view of

a, with axes suitably permuted.

see also

ndarray.t

array property returning the array transposed.

examples

>>>

>>> a = np.array([[1, 2], [3, 4]])

>>> a

array([[1, 2],

[3, 4]])

>>> a.transpose()

array([[1, 3],

[2, 4]])

>>> a.transpose((1, 0))

array([[1, 3],

[2, 4]])

>>> a.transpose(1, 0)

array([[1, 3],

[2, 4]])

對於三維陣列難理解一點:假設 shape(z, x, y)

shape 的 x軸 與 y 軸的轉換比較簡單, 跟二維陣列一樣

in [27]: arr.transpose((0, 2, 1))

out[27]:

array([[[ 0, 4],

[ 1, 5],

[ 2, 6],

[ 3, 7]],

[[ 8, 12],

[ 9, 13],

[10, 14],

[11, 15]]])

對於 z 軸 與 x 軸的變換

in [40]: arr = np.arange(16).reshape((2, 2, 4))

in [41]: arr

out[41]:

array([[[ 0, 1, 2, 3],

[ 4, 5, 6, 7]],

[[ 8, 9, 10, 11],

[12, 13, 14, 15]]])

in [42]: arr.transpose((1, 0, 2))

out[42]:

array([[[ 0, 1, 2, 3],

[ 8, 9, 10, 11]],

[[ 4, 5, 6, 7],

[12, 13, 14, 15]]])

transpose 的變換是根據 shape 進行的

轉換前 shape 是(0, 1, 2)

[[(0,0,0), (0,0,1), (0,0,2), (0,0,3)] // [[[ 0, 1, 2, 3],

[(0,1,0), (0,1,1), (0,1,2), (0,1,3)], // [ 4, 5, 6, 7]],

[(1,0,0), (1,0,1), (1,0,2), (1,0,3)] // [[ 8, 9, 10, 11],

[(1,1,0), (1,1,1), (1,1,2), (1,1,3)]]. //[12, 13, 14, 15]]]

轉換後 shape 是(1, 0, 2), 也就是調換位於 z 軸 和 x 軸的shape

[[(0,0,0), (0,0,1), (0,0,2), (0,0,3)]

(1,0,0), (1,0,1), (1,0,2), (1,0,3)],

[(0,1,0), (0,1,1), (0,1,2), (0,1,3)]

[(1,1,0), (1,1,1), (1,1,2), (1,1,3)]]

將轉換前 shape 對應的值填進去 得到

[1,2,3,4]

[8,9,10,11]

[4,5,6,7]

[12,13,14,15]

so perfect 剛好對應輸出

ESFramework解疑 點滴(不斷補充中)

1.imessageheader的實現在 2006.03.31 msn上有個叫mediar的朋友問我esframework中imessageheader的實現在 答案是,imessageheader在你的具體應用中實現,而不是在esframework框架中。imessageheader僅僅規定了你的...

docker的解疑答惑

此教程,直接來伺服器上部署 1.使用編排工具docker compose 原始碼安裝 和 pip安裝,下面只介紹原始碼安裝 1.1sudo curl l s uname m o usr local bin docker compose 1.2sudo chmod x usr local bin do...

Numpy中的函式

生成用函式 效果np.array x 將輸入資料轉化為乙個ndarray np.array x,dtype 將輸入資料轉化為乙個型別為type的ndarray np.asarray array 將輸入資料轉化為乙個新的 copy ndarray np.ones n 生成乙個n長度的一維全一ndarr...