python - 如果字典数组由“nan”组成,则不返回任何条目
问题描述
我有两个表格文件,如下所示。
主文件:
Food Total
fruit 1500
vegetable 0
meat 0
grain 600
fish 65
和 sub.txt:
Food Item Count Percent
fruit apple 450 30
fruit orange 300 20
fruit banana 750 50
grain rice 120 20
grain maize 480 80
fish salmon 65 100
我想合并sub.txt
到main.txt
,然后将其转换为列中的字典。所以我运行如下代码并生成输出:
>>> import pandas as pd
>>>
>>> main = pd.read_csv("main.txt", sep="\t")
>>> sub = pd.read_csv("sub.txt", sep="\t")
>>>
>>> out = (main.merge(sub, on='Food', how='left')
... .groupby(['Food','Total'])['Item','Count','Percent']
... .apply(lambda x: x.to_dict(orient='records')))
>>>
>>> out
Food Total
fish 65 [{'Item': 'salmon', 'Count': 65.0, 'Percent': ...
fruit 1500 [{'Item': 'apple', 'Count': 450.0, 'Percent': ...
grain 600 [{'Item': 'rice', 'Count': 120.0, 'Percent': 2...
meat 0 [{'Item': nan, 'Count': nan, 'Percent': nan}]
vegetable 0 [{'Item': nan, 'Count': nan, 'Percent': nan}]
dtype: object
从out
对象可以看出,nan
是在没有and信息的时候创建的meat
(vegetable
因为Total
是0)。我试图为那些有nan
. 因此,对于那些拥有 的人来说,理想情况下nan
,我希望得到如下输出:
Food Total
fish 65 [{'Item': 'salmon', 'Count': 65.0, 'Percent': ...
fruit 1500 [{'Item': 'apple', 'Count': 450.0, 'Percent': ...
grain 600 [{'Item': 'rice', 'Count': 120.0, 'Percent': 2...
meat 0 []
vegetable 0 []
dtype: object
但我不知道如何删除整个实体并为带有nan
.
解决方案
我从另一个 post python dataframe to_dict by index 中找到了,排除 NaN。所以我只需要添加dropna()
到apply
函数中。
.apply(lambda x: x.dropna().to_dict(orient='records')))
推荐阅读
- php - 从控制器传递变量以查看并使用变量显示数据
- .net - Visual Studio 社区 2019 不显示设计器视图
- python - QTableWidget:删除或扩展到整行单元格的活动突出显示
- netsuite - 尝试使用 Suitescript 创建发票时的 INVALID_KEY_OR_REF
- css - 如何在 mat-menu 内将 mat-grid 显示为响应式
- laravel - 如何通过流明中的作曲家安装照明/邮件
- flutter - Flutter 在桌面应用程序中的 UI 内拖放
- c# - 在带有选择的 LINQ 中,我可以向前比较下一行并决定选择什么吗?
- sqlite - TypeError:无法读取未定义的属性“then”。插件科尔多瓦的问题?
- vue.js - 有没有办法在 vuejs 中压缩 app.js 文件