首页 > 解决方案 > 如果字典数组由“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.txtmain.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信息的时候创建的meatvegetable因为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.

标签: pythonpandasdictionarymerge

解决方案


我从另一个 post python dataframe to_dict by index 中找到了,排除 NaN。所以我只需要添加dropna()apply函数中。

.apply(lambda x: x.dropna().to_dict(orient='records')))

推荐阅读