[英]How to return column&row index of cell of certain value
index col1 col2 col3
0 0 1 0
1 1 0 1
2 1 1 0
I am just stuck at a task: to find locations(indices) of all cells that equals to 1. I was trying to use such a statement我只是被困在一个任务中:找到等于 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)
my logic is using loops to traverse the colomns and rows separately and concatenate them later however it returns'NoneType' object has no attribute 'append' would you please help me to debug and complete this task我的逻辑是使用循环分别遍历列和行并稍后将它们连接起来但是它返回'NoneType' object 没有属性'append' 请你帮我调试并完成这个任务
Use numpy.where
for indices for index and columns and then select them for cols, idx
lists:将numpy.where
用于索引和列的索引,然后将 select 用于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']
Or use DataFrame.stack
with filtering for final DataFrame:或者使用DataFrame.stack
过滤最终的 DataFrame:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.