【问题标题】:Read JSON to pandas dataframe - Getting ValueError: Mixing dicts with non-Series may lead to ambiguous ordering将 JSON 读取到 pandas 数据框 - 获取 ValueError:将 dicts 与非系列混合可能会导致排序不明确
【发布时间】:2021-02-19 19:48:16
【问题描述】:

我正在尝试将下面的 JSON 结构读入 pandas 数据帧,但它会抛出错误消息:

ValueError:将 dicts 与非系列混合可能会导致排序不明确。

Json 数据: '''

{
"Name": "Bob",
"Mobile": 12345678,
"Boolean": true,
"Pets": ["Dog", "cat"],
"Address": {
"Permanent Address": "USA",
"Current Address": "UK"
},
"Favorite Books": {
"Non-fiction": "Outliers",
"Fiction": {"Classic Literature": "The Old Man and the Sea"}
}
}

''' 我怎样才能做到这一点?我试过下面的脚本...

'''
j_df = pd.read_json('json_file.json')
j_df

with open(j_file) as jsonfile:
    data = json.load(jsonfile)

'''

【问题讨论】:

  • 我需要以pandas数据框的形式导入这个jason数据。我该怎么做?
  • 重复不匹配,所以重新打开。

标签: json pandas


【解决方案1】:

首先从文件中读取 json 并通过DataFrame.explode 传递给json_normalize

import json

with open('json_file.json') as data_file:    
    data = json.load(data_file)  


df = pd.json_normalize(j).explode('Pets').reset_index(drop=True)
print (df)

  Name    Mobile  Boolean Pets Address.Permanent Address  \
0  Bob  12345678     True  Dog                       USA   
1  Bob  12345678     True  cat                       USA   

  Address.Current Address Favorite Books.Non-fiction  \
0                      UK                   Outliers   
1                      UK                   Outliers   

  Favorite Books.Fiction.Classic Literature  
0                   The Old Man and the Sea  
1                   The Old Man and the Sea  

编辑:对于将值写入句子,您可以选择必要的列、删除重复项、创建 numpy 数组和循环:

for x, y in df[['Name','Favorite Books.Fiction.Classic Literature']].drop_duplicates().to_numpy():
    print (f"{x}’s favorite classical iterature book is {y}.")
Bob’s favorite classical iterature book is The Old Man and the Sea.

【讨论】:

  • @NEU - 重要问题,如果使用带有真实数据的解决方案,print (df.head(10).columns) 是什么?
  • 对于json文件->提取会员姓名和最喜欢的经典文学书。打印消息“x最喜欢的经典文学书是y。”-其中x是名字,y是最喜欢的经典文学书
  • 这真的很有帮助。谢谢
  • 如果你可以这样回答:对于 sqlite chinook db 数据库文件 -> 找到员工总数和表员工中唯一标题的数量。 Print“There are total xemployees with y differenttitles.”–将x替换为员工总数,y替换为唯一头衔的数量
  • @NEU - 我认为你不需要this,然后使用我的EDIT 部分,列名已更改
猜你喜欢
  • 2018-09-05
  • 2021-08-20
  • 2021-01-05
  • 2019-11-22
  • 2021-12-25
  • 2019-07-11
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
相关资源
最近更新 更多