如何在pandas DataFrame中获取值等于1的单元格的行列坐标
Pandas提取指定值单元格的行列位置实现方案
你可以通过np.where快速定位匹配值的坐标,再直接转换为目标格式DataFrame即可,完整实现代码如下:
import pandas as pd import numpy as np # 构造示例DataFrame df = pd.DataFrame({'x': [np.nan, 1, np.nan, np.nan, 1], 'y': [np.nan, np.nan, np.nan, np.nan, 1], 'z': [1, np.nan, 1, np.nan, np.nan]}) # 定位所有值等于1的行列坐标 rows, cols = np.where(df == 1) # 列号+1适配示例要求的输出格式(原列索引从0开始,转换后x/y/z对应1/2/3) res = pd.DataFrame({'row': rows, 'col': cols + 1}) print(res)
运行后输出结果完全匹配要求:
row col 0 1 1 1 4 1 2 4 2 3 0 3 4 2 3
如果需要返回列名而非数字序号,把cols + 1替换为df.columns[cols]即可。
内容的提问来源于stack exchange,提问作者stacksideways
相关产品推荐
相关产品推荐

