json - 将 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"}}'
任何想法如何将这些内花括号变成方括号?
解决方案
将值转换为字典,然后转换为 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"]}
推荐阅读
- ios - 让自定义 TableViewCell 的 UIimageView 宽度为单元格宽度的 1/3,单元格高度 = 图像纵横比
- php - 转到 URL 子目录时 CakePHP 应用程序 404
- delphi - 德尔福 64 位 mac os 应用程序
- python - 指定如何分区 dask 数据帧?
- java - Java - 在这种情况下如何正确规避非法访问异常
- regex - 从 EventLog 消息中提取一个句子
- javascript - 如何在 JS/jQuery 中激活新创建的输入
- join - 使用 awk 进行完全外连接
- ios - 制作自定义相机,在我的 App Delegate 中收到“线程 1:信号 SIGBRT”错误
- python - 熊猫合并不匹配:第二个数据框永远不会合并?