Python 3.x 作为dict从数据帧检索非零列

Python 3.x 作为dict从数据帧检索非零列,python-3.x,pandas,Python 3.x,Pandas,给定如下所示的数据帧 cat dog hamster dolphin cat 1 0.5 0 0.25 dog 0.5 1 0 0 hamster 0 0 1 0.5 dolphin 0.25 0 0.5

给定如下所示的数据帧

            cat        dog        hamster    dolphin
cat         1          0.5        0          0.25
dog         0.5        1          0          0
hamster     0          0          1          0.5
dolphin     0.25       0          0.5        1
我想以字典格式获取给定行大于零的列值。例如,对于仓鼠线,结果应为:

{ 'hamster': 1, 'dolphin': 0.5 }
不过,最好省略同名列,因此对于“仓鼠”,这会更好:

{ 'dolphin': 0.5 }

目前,我使用
df[“仓鼠”]接收给定行的所有值。to_dict()
并通过字典理解删除零值,如
{k:v for(k,v)in d.items()(如果v>0}
),但这远不是理想的,因为数据帧的原始大小约为50000 x 50000。pandas中有没有更简单的方法来过滤掉值为0的列(以及名称相同的列,如果容易的话)?

您可以应用于dict,为每行创建一个值作为字典,并将序列作为输出

df.apply(lambda x: x[(x!=0) & (x.keys()!=x.name)].to_dict())

cat        {'dog': 0.5, 'dolphin': 0.25}
dog                         {'cat': 0.5}
hamster                 {'dolphin': 0.5}
dolphin    {'cat': 0.25, 'hamster': 0.5}
或者您可以将上述系列转换为索引为键的字典

df.apply(lambda x: x[(x!=0) & (x.keys()!=x.name)].to_dict()).to_dict()
你得到

 {'cat': {'dog': 0.5, 'dolphin': 0.25},
 'dog': {'cat': 0.5},
 'hamster': {'dolphin': 0.5},
 'dolphin': {'cat': 0.25, 'hamster': 0.5}}
如果使用
1.1.2

{0: {'dog': 0.5, 'dolphin': 0.25},
 1: {'cat': 0.5},
 2: {'dolphin': 0.5},
 3: {'cat': 0.25, 'hamster': 0.5}}
可以显式指定orient参数

df.to_dict('index')