You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python快速生成DataFrame中值为1的行索引字典?

解决方法

直接用pandas的apply方法配合lambda表达式就能一行搞定,不需要循环:

首先定义示例DataFrame:

import pandas as pd

df = pd.DataFrame({'Col1': [0, 1],
                   'Col2': [1, 1],
                   'Col3': [0, 0]}, index=[1, 2])

然后执行以下代码:

result = df.apply(lambda col: col[col == 1].index.tolist()).to_dict()

执行后result就是你要的结果:

{'Col1': [2], 'Col2': [1, 2], 'Col3': []}

原理说明

  • df.apply(lambda col: ...) 遍历DataFrame的每一列,把每一列作为参数传入lambda函数
  • col[col == 1] 筛选出当前列中值为1的行
  • .index.tolist() 将这些行的索引转换为列表
  • 最后调用.to_dict()把处理后的Series转为目标字典,空列会自动生成空列表

内容的提问来源于stack exchange,提问作者JachymDvorak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:05:27