gpt4 book ai didi

python - pd.read_json() 到 pandas 中的数据框

转载 作者:行者123 更新时间:2023-12-04 17:19:33 24 4
gpt4 key购买 nike

我以前从未使用过 json 文件。目前这就是我正在做的:

df = pd.read_json("precincts-with-results.geojson.gz")
df['features']

这是上面的结果:

{'type': 'Feature',
'properties': {'GEOID': '05047-1-A (Oz Wd 1)',
'votes_dem': 79,
'votes_rep': 279,
'votes_total': 366,
'votes_per_sqkm': 54.2,
'pct_dem_lead': -54.6},
'geometry': {'type': 'MultiPolygon',
'coordinates': [[[[-93.88536364311612, 35.483758439321655],
[-93.8840470388143, 35.483727092097084],
[-93.88403177163875, 35.483726728784056],
[-93.88403177478405, 35.48372661335151],
[-93.87956152062023, 35.483586322546344],
[-93.87520339804045, 35.48339873745174],
[-93.87534656033012, 35.480428139370346],
[-93.87604589142236, 35.48045051399295], ...

我想要一个看起来像这样的数据框:

GEOID                   votes_dem     votes_rep     votes_total      votes_per_sqkm       pct_dem_lead
05047-1-A (Oz Wd 1) 79 279 366 54.2 -54.6

您可以在此处下载数据集(大小 264 mb):https://int.nyt.com/newsgraphics/elections/map-data/2020/national/precincts-with-results.geojson.gz

感谢帮助和代码!!

最佳答案

这对我有用

import pandas as pd

filename = 'precincts-with-results.geojson.gz'
df = pd.read_json(filename)
features = df['features']
properties = [_['properties'] for _ in features.values]
collect_properties = {_: list() for _ in properties[0].keys()}
for record in properties:
for col_name, value in record.items():
collect_properties[col_name].append(value)

new_df = pd.DataFrame.from_dict(collect_properties).set_index('GEOID')
print(new_df)

结果看起来像

                        votes_dem  votes_rep  ...  votes_per_sqkm  pct_dem_lead
GEOID ...
05047-1-A (Oz Wd 1) 79.0 279.0 ... 54.2 -54.6
05149-11 - Dutch Creek 6.0 31.0 ... 0.3 -67.6
05081-Franklin Township 53.0 383.0 ... 3.8 -73.3
05027-McNeil City 64.0 68.0 ... 41.9 -2.9
05027-Taylor Township 67.0 342.0 ... 1.7 -65.0
... ... ... ... ...
56007-01-01 173.0 300.0 ... 21.8 -26.1
56045-05-01 70.0 390.0 ... 259.5 -66.7
56045-05-02 67.0 376.0 ... 66.5 -68.1
56045-05-03 63.0 419.0 ... 141.4 -71.5
56041-130 168.0 654.0 ... 1.7 -57.1
[146596 rows x 5 columns]

关于python - pd.read_json() 到 pandas 中的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67096257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com