1 回答

TA貢獻1993條經驗 獲得超6個贊
當您打?。ǖ谝粋€)表時,結果是:
array([list([[1, 4, 8, 6], [8]]), list([[4], [9], [5]]), list([[6], [4]]),
list([[2], [1]])], dtype=object)
即它是一個一維數組,包含4個列表類型的元素。
np.where找不到1實例的原因是它查看每個元素并將其與給定值進行比較。此函數在檢查數組的特定元素時不會“潛入”此對象(不檢查元素的各個子元素(如果它是列表))。
np.where在檢查一個元素(列表類型)時所做的所有事情是檢查:這個元素是否 == 1。既然不是,那么它就被視為不匹配。其他元素也是。
根據 15.07 的評論進行編輯
如果您將表定義為:
table2 = np.array(list([
list([[1,4,8,6], [8,0,0,0], [0,0,0,0]]),
list([[4,0,0,0], [9,0,0,0], [5,0,0,0]]),
list([[6,0,0,0], [4,0,0,0], [0,0,0,0]]),
list([[2,0,0,0], [1,0,0,0], [0,0,0,0]])]))
(所有列表的大小相同),Pandas足夠聰明,可以將其轉換為:
array([[[1, 4, 8, 6],
[8, 0, 0, 0],
[0, 0, 0, 0]],
[[4, 0, 0, 0],
[9, 0, 0, 0],
[5, 0, 0, 0]],
[[6, 0, 0, 0],
[4, 0, 0, 0],
[0, 0, 0, 0]],
[[2, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 0]]])
運行table.shape,你會看到(4, 3, 4)。
然后運行table.dtype,你會看到dtype('int32'),所以它現在是一個“常規”的Numpy int數組。
在這種情況下,np.argwhere(table == 1)找到僅包含1的單元格的索引。
但是你的桌子是如此“奇怪”的情況,熊貓不是為它設計的。
要在這些(嵌套的)列表中找到每個1的索引,您可以遍歷數組(使用nd.iter)并在每個元素內部查找1的索引(如果有)。就像是:
it = np.nditer(table, flags=['f_index', 'refs_ok'])
for x in it:
print(f'Index {it.index}: {x}')
res = [(i, el.index(1)) for i, el in enumerate(x[()]) if 1 in el]
if len(res) == 0:
print(' Nothing found')
else:
print(f' Found at: {res}')
請注意,在x之后有一些奇怪的結構,即[()]。原因是:
您的表是對象的一維數組。
每個元素實際上是一個0 維數組,包含單個 對象(嵌套列表)。
[()]是獲取唯一包含對象的方法。您通過 index訪問元素,但索引值是一個空元組 (沒有實際的索引值)。
對于您的表格,上面的代碼打?。?/p>
Index 0: [[1, 4, 8, 6], [8]]
Found at: [(0, 0)]
Index 1: [[4], [9], [5]]
Nothing found
Index 2: [[6], [4]]
Nothing found
Index 3: [[2], [1]]
Found at: [(1, 0)]
如果需要,請對其進行返工以滿足您的需要。
添加回答
舉報