【发布时间】:2020-03-08 05:40:10
【问题描述】:
在我的 Django 视图中,我想将字典列表加载到 Pandas 数据框中,对其进行操作,再次转储到 dict 并返回此类操作数据作为此视图 JSON 响应的一部分:
def test(request):
pre_pandas = [{'type': 'indoor', 'speed': 1, 'heart_rate': None}, {'type': 'outdoor', 'speed': 2, 'heart_rate': 124.0}, {'type': 'commute', 'speed': 3, 'heart_rate': 666.0}, {'type': 'indoor', 'speed': 4, 'heart_rate': 46.0}]
df = pd.DataFrame(pre_pandas)
# some data manipulation here...
post_pandas = df.to_dict(orient='records')
response = {
'pre_pandas': pre_pandas,
'post_pandas': post_pandas,
}
return JsonResponse(response)
我的方法的问题是 Pandas 的 to_dict() 方法将 Python 的 None 替换为 nan,因此响应中包含 NaN:
{"pre_pandas": [{"type": "indoor", "speed": 1, "heart_rate": null}...], "post_pandas": [{"heart_rate": NaN, "speed": 1,...}]
而 JavaScript 无法处理 NaN。
有没有办法将数据帧转储到 dict,以便输出与构建它的 dict 完全相同?
我可以使用列表 replace() 方法手动调整数据,但感觉很尴尬,而且我需要涵盖所有其他(如果有的话)转换 Pandas 的 to_dict() 方法可能会做的事情。
我也无法将 post_pandas 转储到 JSON,因为我已经在 JsonResponse 中这样做了。
【问题讨论】:
标签: python json django pandas dataframe