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

如何将DataFrame转换为以行索引为键、True列索引为值的字典

生成行索引为键、True值对应列索引列表为值的字典

给定的DataFrame

先还原你提供的DataFrame:

import pandas as pd

df = pd.DataFrame(
    [[False, True, False, True, True, False, True, True, True, False],
     [False, True, False, True, True, True, True, True, False, False]],
    index=[3, 4],
    columns=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
)

解决方案

这里提供两种高效实现方式:

方法1:使用apply + numpy.where

import numpy as np

result = df.apply(lambda row: np.where(row)[0].tolist(), axis=1).to_dict()
  • np.where(row)提取该行中值为True的元素的列索引位置
  • tolist()将索引数组转为列表
  • to_dict()将最终的Series直接转换为目标字典

方法2:使用stack(适合大数据集,性能更优)

result = df.stack().reset_index().groupby('level_0')['level_1'].apply(list).to_dict()
  • stack()过滤掉值为False的元素,同时将列索引转为二级索引
  • reset_index()将多级索引转为普通列(level_0是原行索引,level_1是原列索引)
  • groupby('level_0')['level_1'].apply(list)按行索引分组,收集对应列索引为列表
  • to_dict()转换为目标字典

最终结果

执行后得到的字典为:

{3: [1, 3, 4, 6, 7, 8], 4: [1, 3, 4, 5, 6, 7]}

注:你给出的示例中4对应的列表包含0,但原DataFrame中第4行第0列的值是False,此处为笔误,上述结果为正确输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:05:14