【问题标题】:How to return column&row index of cell of certain value如何返回某个值的单元格的列和行索引
【发布时间】:2022-01-17 09:59:59
【问题描述】:
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”对象没有“附加”属性 请您帮我调试并完成此任务

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用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 过滤最终的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
    

    【讨论】:

    • 栈法厉害了!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多