【问题标题】:How to parse json into panda dataframe如何将json解析成熊猫数据框
【发布时间】:2018-09-11 00:23:46
【问题描述】:

我尝试解析以下 json 结构:

[
 {
"id": 0,
"cuisine": "greek",
"ingredients": [
  "romaine lettuce",
  "black olives",
  "feta cheese crumbles"
]
},
{
"id": 1,
"cuisine": "southern_us",
"ingredients": [
  "plain flour",
  "ground pepper",
  "milk",
  "vegetable oil"
]
}....]

这个 JSON 文件中有数千个值,我想将其解析为 panda 数据帧。考虑到成分键下有一个嵌套列表,我将如何去做。

干杯:)

【问题讨论】:

  • 解析文件应该产生一个基本的python数据结构——一个字典列表等。导入json模块并使用它的load

标签: python json pandas dataframe


【解决方案1】:

或者:

pd.concat(map(pd.DataFrame,json))

例子:

>>> import pandas as pd
>>> json=[
 {
"id": 0,
"cuisine": "greek",
"ingredients": [
  "romaine lettuce",
  "black olives",
  "feta cheese crumbles"
]
},
{
"id": 1,
"cuisine": "southern_us",
"ingredients": [
  "plain flour",
  "ground pepper",
  "milk",
  "vegetable oil"
]
}]
>>> pd.concat(map(pd.DataFrame,json))
       cuisine  id           ingredients
0        greek   0       romaine lettuce
1        greek   0          black olives
2        greek   0  feta cheese crumbles
0  southern_us   1           plain flour
1  southern_us   1         ground pepper
2  southern_us   1                  milk
3  southern_us   1         vegetable oil
>>> 

【讨论】:

  • 传奇!谢谢:)
  • @Hews 谢谢,很高兴我能帮上忙,?
【解决方案2】:

这是dict而不是json的列表

pd.concat([pd.DataFrame(x) for x in js])
Out[156]: 
       cuisine  id           ingredients
0        greek   0       romaine lettuce
1        greek   0          black olives
2        greek   0  feta cheese crumbles
0  southern_us   1           plain flour
1  southern_us   1         ground pepper
2  southern_us   1                  milk
3  southern_us   1         vegetable oil

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 2019-01-01
    • 2019-12-07
    • 1970-01-01
    • 2021-05-02
    • 2023-03-18
    • 2019-08-01
    • 1970-01-01
    • 2014-02-01
    相关资源
    最近更新 更多