Pandas在执行json时删除空值

2024-04-28 05:32:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我实际上有一个pandas数据框,我想将它保存为json格式。 从熊猫的文件上可以看出:

Note NaN‘s, NaT‘s and None will be converted to null and datetime objects will be converted based on the date_format and date_unit parameters

然后使用orient选项records我得到了这样的结果

[{"A":1,"B":4,"C":7},{"A":null,"B":5,"C":null},{"A":3,"B":null,"C":null}]

是否可以改为:

[{"A":1,"B":4,"C":7},{"B":5},{"A":3}]'

谢谢你


Tags: and文件数据nonejsonpandasdate格式
3条回答

我遇到了同样的问题,我的解决方案是使用json模块而不是pd.DataFrame.to_json()

我的解决办法是

  1. 将DataFrame转换为dict时删除NaN值,然后
  2. 使用json.dumps()将dict转换为json

代码如下:

import pandas as pd
import json
from pandas import compat

def to_dict_dropna(df):
   return {int(k): v.dropna().astype(int).to_dict() for k, v in compat.iteritems(df)}

json.dumps(to_dict_dropna(df))

下面是您想要的,实际上我们创建了一个非NaN值的列表,然后在上面调用to_json

In [136]:
df.apply(lambda x: [x.dropna()], axis=1).to_json()

Out[136]:
'{"0":[{"a":1.0,"b":4.0,"c":7.0}],"1":[{"b":5.0}],"2":[{"a":3.0}]}'

这里需要创建一个列表,否则它将尝试将结果与原始df形状对齐,这将重新引入NaN值,这是您要避免的:

In [138]:
df.apply(lambda x: pd.Series(x.dropna()), axis=1).to_json()

Out[138]:
'{"a":{"0":1.0,"1":null,"2":3.0},"b":{"0":4.0,"1":5.0,"2":null},"c":{"0":7.0,"1":null,"2":null}}'

同时对dropna的结果调用list将用形状广播结果,如填充:

In [137]:
df.apply(lambda x: list(x.dropna()), axis=1).to_json()

Out[137]:
'{"a":{"0":1.0,"1":5.0,"2":3.0},"b":{"0":4.0,"1":5.0,"2":3.0},"c":{"0":7.0,"1":5.0,"2":3.0}}'

上面的解决方案实际上并没有以“records”格式生成结果。此解决方案还使用json包,但生成的结果正好是原始问题中要求的结果。

import pandas as pd
import json

json.dumps([row.dropna().to_dict() for index,row in df.iterrows()])

此外,如果要包含索引(并且您使用的是Python3.5+),可以执行以下操作:

json.dumps([{'index':index, **row.dropna().to_dict()} for index,row in df.iterrows()])

相关问题 更多 >