我正在使用一個表示為大型真值矩陣的 pandas 資料框。
a1 b2 c3 d4 e5 f6
a1 True True False True False True
b2 True True False True True True
c3 False False True True True False
d4 True True True True False True
e5 False True True False True False
f6 True True False True False True
我可以通過以下方式獲取行數及其各自的True計數:
df[df == True].count(axis=0)
哪個會回傳:
a1: 4
b2: 5
c3: 3
d4: 5
e5: 3
f6: 4
同樣,我可以獲得具有最多 True 值的索引,其名稱為:
max_count = max(df[df == True].count(axis=0)
id = df[df == True].count(axis=0).idxmax(axis=0)
哪個回傳max_count=5,id=b2
我很好奇如何查詢該行以回傳串列中所有具有 True 的索引。
理想的輸出是:
ids = [a1, b2, d4, e5, f6]
我試過這個:
ids = df[id == True].index.tolist()
這導致了一個關鍵錯誤和上述的許多變化。
uj5u.com熱心網友回復:
首先,因為這里有一個布爾矩陣,所以可以使用sumwith axis=1 來獲取每個行索引的 True 值的計數。
df.sum(axis=1)
輸出:
a1 4
b2 5
c3 3
d4 5
e5 3
f6 4
dtype: int64
現在,讓我們找到“所有”具有最多 True 值的索引,使用np.where:
max_true_index = df.index[np.where(df.sum(axis=1) == df.sum(axis=1).max())]
max_true_index 回傳:
Index(['b2', 'd4'], dtype='object')
最后,讓我們回傳在這兩個值中或從這個串列中具有 True 的所有索引:
df.index[df[max_true_index].all(axis=1)]
輸出:
Index(['a1', 'b2', 'd4', 'f6'], dtype='object')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/472056.html
