index col1 col2 col3
0 0 1 0
1 1 0 1
2 1 1 0
我只是被困在一個任務中:找到等于 1 的所有單元格的位置(索引)。我試圖使用這樣的陳述句
column_result=[]
row_result=[]
for column in df:
column_result=column_result.append(df.index[df[i] != 0])
for row in df:
row_result=row_result.append(df.index[df[i]!=0)
我的邏輯是使用回圈分別遍歷列和行并稍后將它們連接起來但是它回傳'NoneType'物件沒有屬性'append'你能幫我除錯并完成這個任務嗎
uj5u.com熱心網友回復:
用于numpy.where索引和列的索引,然后為cols, idx串列選擇它們:
i, c = np.where(df.ne(0))
cols = df.columns[c].tolist()
idx = df.index[i].tolist()
print (idx)
[0, 1, 1, 2, 2]
print (cols)
['col2', 'col1', 'col3', 'col1', 'col2']
或者使用DataFrame.stack過濾最終資料幀:
s = df.stack()
df1 = s[s.ne(0)].rename_axis(['idx','cols']).index.to_frame(index=False)
print (df1)
idx cols
0 0 col2
1 1 col1
2 1 col3
3 2 col1
4 2 col2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/414380.html
標籤:
