首页 > 解决方案 > 将 pandas.df 转换为这种特定的 JSON 格式

问题描述

考虑这个熊猫数据框:

This_df = pandas.DataFrame({'SYM': {0: 'this_string', 1: 'this_string', 2: 'this_string'},
 'DATE': {0: 'NaN', 1: 'NaN', 2: 'NaN'},
 'YEST': {0: 'NaN', 1: 'NaN', 2: 'NaN'},
 'other_DATE': {0: 'NaN', 1: 'NaN', 2: 'NaN'},
 'SIZE': {0: 'NaN', 1: 'NaN', 2: 'NaN'},
 'ACTIVITY': {0: '2019-09-27 14:18:28.000700 UTC',
  1: '2019-09-27 14:18:28.000700 UTC',
  2: '2019-09-27 14:18:28.000600 UTC'}})

我正在尝试将其保存在文件中,以使文件的内容如下所示:

'{"SYM": ["this_string","this_string","this_string"],"DATE": ["NaN","NaN","NaN"],"YEST": ["NaN","NaN","NaN"],"other_DATE": ["NaN","NaN","NaN"],"SIZE": ["NaN","NaN","NaN"],"ACTIVITY": ["2019-09-27 14:18:28.000700 UTC","2019-09-27 14:18:28.000700 UTC","2019-09-27 14:18:28.000600 UTC"]}'

但是做:

pandas.DataFrame(This_df).to_json(orient = 'columns')                                                                      

返回:

'{"SYM":{"0":"this_string","1":"this_string","2":"this_string"},"DATE":{"0":"NaN","1":"NaN","2":"NaN"},"YEST":{"0":"NaN","1":"NaN","2":"NaN"},"other_DATE":{"0":"NaN","1":"NaN","2":"NaN"},"SIZE":{"0":"NaN","1":"NaN","2":"NaN"},"ACTIVITY":{"0":"2019-09-27 14:18:28.000700 UTC","1":"2019-09-27 14:18:28.000700 UTC","2":"2019-09-27 14:18:28.000600 UTC"}}'

任何想法如何将这些内花括号变成方括号?

标签: jsonpandas

解决方案


将值转换为字典,然后转换为 json,因为to_json(orient = 'list')未实现:

import pandas as pd
import json

#sample data
df = pd.DataFrame(This_df)

j = json.dumps(df.to_dict(orient = 'list'))
print (j)

{"SYM": ["this_string", "this_string", "this_string"], "DATE": ["NaN", "NaN", "NaN"], "YEST": ["NaN", "NaN", "NaN"], "other_DATE": ["NaN", "NaN", "NaN"], "SIZE": ["NaN", "NaN", "NaN"], "ACTIVITY": ["2019-09-27 14:18:28.000700 UTC", "2019-09-27 14:18:28.000700 UTC", "2019-09-27 14:18:28.000600 UTC"]}

推荐阅读