如何从 pandas 数据框中提取列表或字典中的非NA值 [英] How to extract non NA values in a list or dict from a pandas dataframe

查看:96
本文介绍了如何从 pandas 数据框中提取列表或字典中的非NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的df,

df

    AAA BBB CCC
0   4   10  100
1   5   20  50
2   6   30  -30
3   7   40  -50

df_mask = pd.DataFrame({'AAA' : [True] * 4, 'BBB' : [False] * 4,'CCC' : [True,False] * 2})df.where(df_mask)

    AAA BBB CCC
0   4   NaN 100.0
1   5   NaN NaN
2   6   NaN -30.0
3   7   NaN NaN

我试图像这样提取非null值.

I am trying to extract the non null values like this.

我尝试过, df[df.where(df_mask).notnull()].to_dict()但它给出了所有值

I tried, df[df.where(df_mask).notnull()].to_dict() but it gives all the values

我的预期输出是

{'AAA': {0: 4, 1: 5, 2: 6, 3: 7},
 'CCC': {0: 100.0, 2: -30.0}}

推荐答案

在这里使用agg:

v = df.where(df_mask).agg(lambda x: x.dropna().to_dict())

在较旧的版本中,apply会执行相同的操作(尽管速度较慢).

On older versions, apply does the same thing (albeit a bit slower).

v = df.where(df_mask).apply(lambda x: x.dropna().to_dict())

现在,为最后一步过滤出带有空字典的行:

And now, filter out rows with empty dictionaries for the final step:

res = v[v.str.len() > 0].to_dict()

print(res)
{'AAA': {0: 4.0, 1: 5.0, 2: 6.0, 3: 7.0}, 'CCC': {0: 100.0, 2: -30.0}}


另一个免费申请选项是dict-comprehension:


Another apply-free option is a dict-comprehension:

v = df.where(df_mask)  
res = {k : v[k].dropna().to_dict() for k in df} 

print(res)
{'AAA': {0: 4, 1: 5, 2: 6, 3: 7}, 'BBB': {}, 'CCC': {0: 100.0, 2: -30.0}}

请注意,这个(略)简单的解决方案保留了具有空值的键.

Note that this (slightly) simpler solution retains keys with empty values.

这篇关于如何从 pandas 数据框中提取列表或字典中的非NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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