python - 复杂的 json 到 pandas 数据框
问题描述
有很多关于 json 到 pandas 数据框的问题,但没有一个能解决我的问题。我正在练习这个看起来像这样的复杂 json 文件
{
"type" : "FeatureCollection",
"features" : [ {
"Id" : 265068000,
"type" : "Feature",
"geometry" : {
"type" : "Point",
"coordinates" : [ 22.170376666666666, 65.57273333333333 ]
},
"properties" : {
"timestampExternal" : 1529151039629
}
}, {
"Id" : 265745760,
"type" : "Feature",
"geometry" : {
"type" : "Point",
"coordinates" : [ 20.329506666666667, 63.675425000000004 ]
},
"properties" : {
"timestampExternal" : 1529151278287
}
} ]
}
我想将此 json 直接转换为 pandas 数据帧,使用pd.read_json()
我的主要目标是提取 Id、坐标和时间戳外部。由于这是非常复杂的 json,正常的 json 方式pd.read_json()
根本不会给出正确的输出。你能建议我吗,在这种情况下我该如何解决。预期的输出是这样的
Id,Coordinates,timestampExternal
265068000,[22.170376666666666, 65.57273333333333],1529151039629
265745760,[20.329506666666667, 63.675425000000004],1529151278287
解决方案
您可以阅读 json 以将其加载到字典中。然后,使用字典理解,将您想要的属性提取为列 -
import json
import pandas as pd
_json = json.load(open('/path/to/json'))
df_dict = [{'id':item['Id'], 'coordinates':item['geometry']['coordinates'],
'timestampExternal':item['properties']['timestampExternal']} for item in _json['features']]
extracted_df = pd.DataFrame(df_dict)
>>>
coordinates id timestampExternal
0 [22.170376666666666, 65.57273333333333] 265068000 1529151039629
1 [20.329506666666667, 63.675425000000004] 265745760 1529151278287
推荐阅读
- firebase - 在 Firebase 上存储数据以供稍后查询
- c# - 尝试发布数据但不断收到 HTTP 错误 404
- android - Android SharedPrefences 一个键的多个值
- graphql - 如何迁移现有存储过程以使用 graphql
- hyperledger-fabric - 从织物样本构建平衡转移时,签名集不满足策略 /Channel/Application/Org1/Admins
- python - 如何将x轴列为国家而不是python中的数字
- java - EnableGlobalMethodSecurity 注释中的运行时条件 prePostEnable
- asp.net-core - 集合中的 ViewModel 对象类型属性在 POST 上为空
- macos - OSX 勾选菜单栏复选框
- python - 在 Python 中即时实现加权平均