給定一個大小為 MxN 的數組和一個大小為 Mx1 的數組,我想用 MxN 計算一個布爾數組。import numpy as npM = 2N = 3a = np.random.rand(M, N) # The values doesn't matterb = np.random.choice(a=N, size=(M, 1), replace=True)# b =# array([[2],# [1]])# I found this way to compute the boolean array but I wonder if there's a fancier, elegant wayindex_array = np.array([np.array(range(N)), ]*M)# Create an index array# index_array = # array([[0, 1, 2],# [0, 1, 2]])#boolean_array = index_array == b# boolean_array =# array([[False, False, True],# [False, True, False]])#所以我想知道是否有一種更奇特的 pythonic 方式來做到這一點
1 回答

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
您可以通過直接廣播與單個 1d 范圍的比較來簡化:
M = 2
N = 3
a = np.random.rand(M, N)
b = np.random.choice(a=N, size=(M, 1), replace=True)
print(b)
array([[1],
[2]])
b == np.arange(N)
array([[False, True, False],
[False, False, True]])
通常,廣播在這些情況下很方便,因為它使我們不必創建形狀兼容的數組來執行與其他數組的操作。對于生成的數組,我可能會改為使用以下內容:
np.broadcast_to(np.arange(N), (M,N))
array([[0, 1, 2],
[0, 1, 2]])
盡管如前所述,NumPy 使這里的生活更輕松,因此我們不必為此擔心。
添加回答
舉報
0/150
提交
取消