根据 pandas 中DataFrame的结果创建字典 [英] Create dictionary from results of DataFrame in pandas

查看:58
本文介绍了根据 pandas 中DataFrame的结果创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,结果如下.实际显示的样本数据帧要大得多.我想获取一个字典(或其他结构,如果它会更快),其值是所有通过条件的项目(位于列标题中),键是数据帧行.

I have a dataframe with results as below. Sample dataframe shown actual one is much larger. I want to get a dictionary (or another structure if it will be faster) with the values being all the items that pass the criteria (located in columns headers) and the keys being the dataframe rows.

    AAPL    GOOG    MSFT    AMZN    FB
1   NaN      NaN    9.731   NaN     NaN
2   NaN      4.5    NaN     3.486   NaN
3   4.331    NaN    NaN     3.26    5.967
4   NaN      NaN    NaN      NaN    3.61

我想要的结果如下

{1:[MSFT], 2:[GOOG,AMZN], 3:[AAPL, AMZN, FB], 4:[FB]}

推荐答案

在性能方面可能不是最好的,但是您可以使用以下行列:

Maybe not the best in terms of performance, but you could use iterrows:

import numpy as np
results = {}
for i, row in df.iterrows():
    results[i] = list(df.columns[~np.isnan(row)])

这篇关于根据 pandas 中DataFrame的结果创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆