首页 > 解决方案 > 复杂的 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

标签: pythonjsonpandasdataframe

解决方案


您可以阅读 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 

推荐阅读