【问题标题】:Complex json to pandas dataframe复杂的 json 到 pandas 数据框
【发布时间】:2018-06-19 05:05:36
【问题描述】:

有很多关于 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
    }
  } ]
}

我想使用pd.read_json() 直接将此 json 转换为 pandas 数据帧我的主要目标是提取 Id、坐标和时间戳外部。由于这是非常复杂的 json,pd.read_json() 的正常方式根本不会给出正确的输出。你能建议我吗,在这种情况下我该如何解决。预期的输出是这样的

Id,Coordinates,timestampExternal
265068000,[22.170376666666666, 65.57273333333333],1529151039629
265745760,[20.329506666666667, 63.675425000000004],1529151278287

【问题讨论】:

  • 我不明白从计算机的角度来看,一个结构是如何被认为是复杂的。

标签: python json pandas dataframe


【解决方案1】:

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

【讨论】:

  • @user3280146 如果它符合您的目的,您可以接受答案。
【解决方案2】:

您可以直接读取 json,然后将 features 数组作为字典传递给 pandas,如下所示:

代码:

import json

with open('test.json', 'rU') as f:
    data = json.load(f)

df = pd.DataFrame([dict(id=datum['Id'],
                        coords=datum['geometry']['coordinates'],
                        ts=datum['properties']['timestampExternal'],
                        )
                   for datum in data['features']])
print(df)

结果:

                                     coords         id             ts
0   [22.170376666666666, 65.57273333333333]  265068000  1529151039629
1  [20.329506666666667, 63.675425000000004]  265745760  1529151278287

【讨论】:

  • 谢谢,但我如何只制作 ID、坐标和时间戳外部列,而不是获取所有内容。我将为我的预期输出编辑问题
猜你喜欢
  • 2023-03-11
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 2019-08-16
  • 2017-05-14
  • 1970-01-01
相关资源
最近更新 更多