亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 numpy bool 數組作為另一個 arry 的索引

使用 numpy bool 數組作為另一個 arry 的索引

大話西游666 2023-08-15 17:04:24
編輯我的問題以使其更加清晰,因為我無法獲得第一個工作答案。我正在嘗試制作一個 N 維查找表,根據 N 個 True/False 值的輸入列表從中查找一個值。為此,我創建了一個 N 維數組,其中每個維度的長度為 2 - 一個值表示 False (=0),一個值表示 True (=1)import numpy as npimport randomdims = 3values = range(pow(2,dims))lookup=np.reshape(values,np.tile(2,dims)) #this makes a 2x2x2x... arraycondition=random.choices([True,False],k=dims) #this makes a 1d list of bools條件中的布爾值現在應該指定要查找的索引。以 N=3 為例:如果條件 =(True,False,True),我想要查找[1,0,1]。只需使用lookup[condition.astype(int)]不起作用,因為 numpy 不會將 1x3 數組解釋為索引。lookup[condition[0],condition[1],condition[2]]作品。但我還沒弄清楚如何在 N 維上寫這個
查看完整描述

1 回答

?
largeQ

TA貢獻2039條經驗 獲得超8個贊

手動將其轉換為 int 元組可以實現您所尋求的索引。測試下面的代碼。


import numpy as np


# your example had d=3, but you may have something else.

# this is just creation of some random data...

d=3

answers = np.random.normal(size=[2] * d)

truth = tuple(np.random.choice([True, False], replace=True, size=d))


# manual conversion to int-tuple is needed, for numpy to understand that it

# is a indexing tuple.

# the box at the top of https://numpy.org/doc/stable/reference/arrays.indexing.html 

# says that tuple indexing is just like normal indexing, and in that case, we 

# need to have normal ints.

idx = tuple(int(b) for b in truth)

answer = answers[idx]

print(answer)


查看完整回答
反對 回復 2023-08-15
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號