numpy 一維矩陣轉置問題

2021-10-02 04:42:07 字數 1560 閱讀 1298

numpy中,我們如果直接對一維行矩陣轉置,會出現問題,以為 1-d array 的 shape 是 (d,) ,而不是 (1,d) , 轉置後仍為 (d,)

這時,可以採用 numpy.expand_dims() 函式對一維矩陣的 shape 進行操作,使其變成 (1,d)

示例

d=np.array([1

,2,3

,4])

print

('d.shape'

,d.shape)

print

('d.t.shape'

,d.shape)

print

('d='

,d)print

('d.t='

,d)

結果

d.shape (4,

)d.t.shape (4,

)d=[1

234]

d.t=[1

234]

不難發現,轉置後的維度沒有發生改變

expand_dims後的shape是(1,9),a.t就沒有問題了

d=np.expand_dims(d,axis=0)

print

('d.shape'

,d.shape)

print

('d.t.shape'

,d.t.shape)

print

('d='

,d)print

('d.t='

,d)

結果

d.shape (1,

4)d.t.shape (4,

1)d=[

[123

4]]d.t=[[

1][2

][3]

[4]]

d=d[np.newaxis,:]

#equivalent to np.expand_dims(x, axis=0)

print

('d.shape'

,d.shape)

print

('d.t.shape'

,d.t.shape)

print

('d='

,d)print

('d.t='

,d)

結果

d.shape (1,

4)d.t.shape (4,

1)d=[

[123

4]]d.t=[[

1][2

][3]

[4]]

也可以

d=d[

:,np.newaxis]

#equivalent to np.expand_dims(x, axis=1)

print

('d='

,d)

結果

d=[[

1][2

][3]

[4]]

不用numpy實現矩陣轉置

給你乙個二維整數陣列 matrix,返回 matrix 的 轉置矩陣 矩陣的 轉置 是指將矩陣的主對角線翻轉,交換矩陣的行索引與列索引。示例 1 輸入 matrix 1,2,3 4,5,6 7,8,9 輸出 1 4,7 2 5,8 3 6,9 示例 2 輸入 matrix 1,2,3 4,5,6 輸...

求轉置矩陣問題

描述 求乙個三行三列的轉置矩陣。輸入第一行乙個整數n 20,表示有n組測試資料,下面是n組資料 每組測試資料是九個整型數 每個數都不大於10000 分別為矩陣的的每項 輸出每組測試資料的轉置矩陣 請在每組輸出之後加乙個換行 樣例輸入 21 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 ...

Numpy陣列轉置

numpy陣列轉置很容易,兩種種寫法 np array np.array 1,2 3,4 np array.transpose np.transpose np array 但是一維陣列轉置的時候有個坑,光transpose沒有用,需要指定shape引數 array 1d np.array 1,2 p...