【问题标题】:Geopandas with df带 df 的 Geopandas
【发布时间】:2021-06-19 05:15:33
【问题描述】:

我有包含location, side_a, and side_b 的数据框,它们是参与战争的国家。 我还有每场战争的死亡人数、开始年份等详细信息。

假设我想使用 geopandas 显示每个州的死亡人数,我该怎么做? 我尝试使用此代码,但它只是给了我一张世界图(列 = 死亡人数):

fig, ax = plt.subplots(1, 1)
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world = world[(world.pop_est>0) & (world.name!="Antarctica")]
world[column] = df[column]
world.plot(column=column, ax=ax, legend=True)

例如,我希望这个 df 变成一个所有状态都有颜色的图表:

war_index location death number
1 India, China 20
2 India 10

然后中国将被涂上一种颜色代表 10,印度另一种颜色代表 30 其余的不会上色

【问题讨论】:

    标签: python pandas geopandas


    【解决方案1】:

    要走的路是在world 中添加一个包含死亡人数的列。因此,首先您需要计算每个国家/地区df 的总死亡人数。您可以通过拆分location 中的字符串来做到这一点。然后分解该列并在该列上运行groupby。随后,您可以使用pd.merge 合并名称/位置上的数据框,然后通过death number 绘制world

    import geopandas as gpd
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame([ { "war_index": 1, "location": "India, China", "death number": 20 }, { "war_index": 2, "location": "India", "death number": 10 } ])
    df['location'] = df['location'].str.split(', ')
    df = df.explode('location').groupby('location').agg('sum').reset_index()
    
    world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
    world = world[(world.pop_est>0) & (world.name!="Antarctica")]
    world = pd.merge(world,df[['location','death number']], left_on='name', right_on='location', how='left')
    
    fig, ax = plt.subplots(1, 1)
    world.plot(column='death number', ax=ax, legend=True)
    

    结果:

    如果你也想向全世界展示,可以将death number列中的nan替换为0。

    world['death number'] = world['death number'].fillna(0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 2021-06-21
      • 2019-12-31
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多