将pandas.df转换为这种特定的JSON格式

时间:2019-12-27 10:02:56

标签: json pandas

考虑此熊猫数据框:

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"}}'

有什么主意如何将这些内花括号变成方形吗?

1 个答案:

答案 0 :(得分:2)

将值转换为字典,然后转换为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"]}