python - 使用 pandas DataFrame 打开 JSON 文件
问题描述
对不起这个琐碎的问题:
我有一个 json 文件first.json
,我想用以下命令打开它pandas.read_json
:
df = pandas.read_json('first.json')
给我下一个结果:
我需要的结果是一行以键('name'、'street'、'geo'、'servesCuisine' 等)作为列。我试图改变不同的“ orient
”参数,但它没有帮助。我怎样才能达到所需的DataFrame
格式?
这是我的 json 文件中的数据:
{
"name": "La Continental (San Telmo)",
"geo": {
"longitude": "-58.371852",
"latitude": "-34.616099"
},
"servesCuisine": "Italian",
"containedInPlace": {},
"priceRange": 450,
"currenciesAccepted": "ARS",
"address": {
"street": "Defensa 701",
"postalCode": "C1065AAM",
"locality": "Autonomous City of Buenos Aires",
"country": "Argentina"
},
"aggregateRatings": {
"thefork": {
"ratingValue": 9.3,
"reviewCount": 3
},
"tripadvisor": {
"ratingValue": 4,
"reviewCount": 350
}
},
"id": "585777"
}
解决方案
你可以试试
with open("test.json") as fp:
s = json.load(fp)
# flattened df, where nested keys -> column as `key1.key2.key_last`
df = pd.json_normalize(s)
# rename cols to innermost key only (be sure you don't overwrite cols)
cols = {col:col.split(".")[-1] for col in df.columns}
df = df.rename(columns=cols)
输出:
name servesCuisine priceRange currenciesAccepted id ... country ratingValue reviewCount ratingValue reviewCount
0 La Continental (San Telmo) Italian 450 ARS 585777 ... Argentina 9.3 3 4 350
推荐阅读
- json - 快速将json数组解码为对象
- arrays - 谷歌表格 - 根据具有我选择日期的另一个单元格更改单元格文本
- excel - 将唯一值添加到从 PowerBI 中的多个表中检索到的列
- flutter - onPressed of an Image 我想将该图像放在其他页面的容器中,我该如何实现?
- haskell - 在 Haskell 中区分 [Char] 和 [[Char]] 的问题
- node.js - 基本快递服务器评论在顶部
- python - 如何在 Python 交互模式下启用命令行编辑?
- git - 无法将代码推送到 github 上的新分支
- python - ASR - Speech to Text - 如何通过将标签张量与音频样本数组的长度对齐来预处理音频文件的文字转录标签
- django - 如何重新组合 django 中的某些列?