python中兩個不同shape的陣列間運算規則

2021-09-29 14:40:21 字數 1993 閱讀 5804

宣告:本部落格討論的陣列間運算是指四則運算,如:a+b、a-b、a*b、a/b,不包括 a.dot(b) 等運算,由於 numpy 和 tensorflow 中都遵循相同的規則,本部落格以 numpy 為例。

眾所周知,相同 shape 的兩個陣列間運算是指兩個陣列的對應元素相加。我們經常會碰到一些不同 shape 的陣列間運算。那麼,任何兩個不同 shape 的陣列都能運算麼?又遵循什麼樣的運算規則?

shape 與維數:如 a:[1,2,3],則 shape=(3, ),維數為1;b:[[1,2,3],[4,5,6]],則shape=(2,3),維數為2

運算條件:設a為低維陣列,b為高維陣列,則a和b能運算的充分條件是:a.shape[-1]=b.shape[-1]、a.shape[-2]= b.shape[-2]、...(a可以作為b的乙個元素),或者 a.shape=(m,1)(或a.shape=(m, )) 且b.shape=(1,n) (a為行向量,b為列向量

運算規則:

如需改變陣列 shape,可呼叫 reshape() 函式,如下:

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

b=a.reshape([-1,1]) #a.shape=(3,2),b.shape=(6,1)

(1)陣列與數字之間的運算

a=np.array([1,1,1])

b=np.array([[1,1,1],[2,2,2]])

c=a+1

d=b+1

print("c=a+1\n",c)

print("d=b+1\n",d)

c=a+1

[2 2 2]

d=b+1

[[2 2 2]

[3 3 3]]

補充:shape=(1, ) 的陣列可以與任意 shape 的陣列運算,運算規則同數字與陣列的運算。

(2)行向量與列向量之間的運算

a=np.array([[1,2,3]]) #或 a=np.array([1,2,3])

b=np.array([[1],[2],[3],[4],[5]])

c=a+b

print("c=a+b",c)

c=a+b

[[2 3 4]

[3 4 5]

[4 5 6]

[5 6 7]

[6 7 8]]

(3)1維陣列與高維陣列之間的運算

a=np.array([1,1,1])

b=np.array([[1,1,1],[2,2,2]])

c=np.array([[1,1,1],[2,2,2],[3,3,3]])

d=a+b

e=a+c

print("d=a+b\n",d)

print("e=a+c\n",e)

d=a+b

[[2 2 2]

[3 3 3]]

e=a+c

[[2 2 2]

[3 3 3]

[4 4 4]]

(4)高維陣列之間的運算

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

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

c=a+b

print("c=a+b\n",c)

c=a+b

[[[2 2 2]

[4 4 4]]

[[4 4 4]

[6 6 6]]]

python中取兩個列表中不同的元素

print i for i in c if i not in b 注 b為報表中輸出的酒店列表,c為酒店提供的列表,現在c為2865家,而報表中輸出的只有2842家。有23家沒有輸出,需要確認這23家是不是真的沒有price資料。目前工作中客戶總是提出增加hotel列表的需求,測試時每次都需要抽查新...

Python對比兩個txt檔案的不同

提前準備好三個txt檔案 1.txt 和 2.txt 為對比檔案 diff.txt 為儲存不同內容檔案 以讀取方式開啟兩個txt檔案 f1 open 1.txt r f2 open 2.txt r 讀取兩個txt檔案 txt1 f1.read txt2 f2.read 按行的方式讀取txt檔案 tx...

找出兩個List 中不同的元素

public class collectionutil 找出兩個集合中不同的元素 param collmax param collmin return public static collection getdifferent collection collmax,collection collmi...