简体   繁体   English

如何返回某个值的单元格的列和行索引

[英]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.

相关问题 如何使用用户输入来选择行列和返回单元格值? - How to use user input to select row column and return cell value? 如何使用 Pandas 中的索引列从“其他”行返回值 - How to return value from "other" row using index column in Pandas 熊猫:如何查找其单元格值与某个值匹配的一列的值索引 - Pandas: How to find index of value of one column whose cell value matches certain value Excel:如何在包含字符串的列中查找单元格并在另一列行中返回单元格的值? - Excel: How to find cell in a column that contains a string and return value of a cell in another column of row? 如何在包含字符串的列中查找单元格并在另一行中返回单元格的值? - How to find cell in a column that contains a string and return value of a cell in another of row? Pandas:当列达到另一列的某个值时,如何返回行值? - Pandas: How do I return a row value once a column reaches a certain value of another column? 如何遍历 Pandas DF 中的列以检查某个值并返回同一行但来自不同列的值? - How to iterate over a column in a Pandas DF to check for a certain value and return a value in the same row but from a different column? 熊猫按行号(不是行索引)和列名获取单元格值 - Pandas get cell value by row NUMBER (NOT row index) and column NAME 如何按单元格值获取数据框列索引 - how to get dataframe column index by cell value 在Pandas数据帧中查找任何单元格值= = x,并返回单元格值,列标题,行和相邻单元格值 - Find any cell values >= x in Pandas dataframe and return cell value, column header, row and neighbouring cell value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM