【问题标题】:Convert json data to csv with python3 but it doesn't work使用python3将json数据转换为csv但它不起作用
【发布时间】:2019-05-26 01:15:22
【问题描述】:

我有一个包含一组数字的大型数据集

从服务器获取数据

每一行数据是这样的:

{"body_data":[
{'height': 170.00, 'weight': 165.00, 'blood': 3.00, 'sugar': 100.02, 'fat': 36.02, 'time_object': 1544443260000},
{'height': 170.00, 'weight': 165.00, 'blood': 3.00, 'sugar': 100.02, 'fat': 36.02, 'time_object': 1544443260000},
],"symbol":"DATA_FAT","empty":false}

我尝试将数据保存为 *.json 格式,然后将其导入为新文件并用 csv 重写,但出现错误。

我用 pandas 尝试了以下代码:

df = pd.DataFrame.from_dict(data, orient='index',columns=['open', 'height', 'weight', 'blood', 'sugar', 'fat', 'time_object'])

它给了我以下错误:

 File "pandas/_libs/src/inference.pyx", line 1517, in pandas._libs.lib.to_object_array
TypeError: object of type 'bool' has no len()

谁能帮帮我

【问题讨论】:

  • 请分享您的代码。
  • 请也粘贴完整的错误信息

标签: python json pandas csv


【解决方案1】:

我相信你需要选择嵌套键body_data

df = pd.DataFrame(data['body_data'])
print (df)
   blood    fat  height   sugar    time_object  weight
0    3.0  36.02   170.0  100.02  1544443260000   165.0
1    3.0  36.02   170.0  100.02  1544443260000   165.0

如果想要更改列的顺序(open 键不在样本数据中,所以 NaNs 在输出中):

df = pd.DataFrame(data['body_data'],
                  columns=['open', 'height', 'weight', 'blood', 'sugar', 'fat', 'time_object'])
print (df)
   open  height  weight  blood   sugar    fat    time_object
0   NaN   170.0   165.0    3.0  100.02  36.02  1544443260000
1   NaN   170.0   165.0    3.0  100.02  36.02  1544443260000

【讨论】:

  • 非常感谢您解决了问题,是的,您是对的,我选择了 body_data,现在它运行良好。
  • @Abdullah.F - 欢迎您!如果我的回答有帮助,请不要忘记accept。谢谢。
猜你喜欢
  • 2017-06-04
  • 2020-02-13
  • 2022-01-11
  • 1970-01-01
  • 2014-04-11
  • 2018-12-08
  • 2015-08-23
  • 1970-01-01
  • 2020-09-03
相关资源
最近更新 更多