给定如下的数据帧
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 }不过,省略同名的列会更好,所以对于'hamster',这会更好:
{ 'dolphin': 0.5 }目前,我使用df["hamster"].to_dict()接收给定行的所有值,并使用字典理解(如{k: v for (k,v) in d.items() if v > 0 } )删除零值,但这并不理想,因为dataframe的原始大小约为50000 x 50000。pandas中有没有更简单的方法来筛选出值为0的列(如果容易的话,还有同名的列)?
发布于 2020-10-03 00:42:50
您可以应用to_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}}如果您使用pandas 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')https://stackoverflow.com/questions/64175070
复制相似问题