简体   繁体   English

如何使用 plotly.express 创建用于映射的 ID

[英]How to Create id for Mapping with plotly.express

I have a dataframe "states" that has each states's child poverty rate and json file called "us_states".我有一个 dataframe“州”,其中包含每个州的儿童贫困率和名为“us_states”的 json 文件。 I want to create a choropleth map using plotly express but I'm struggling to create the id column.我想使用 plotly express 创建一个 choropleth map 但我正在努力创建 id 列。 Here is my entire code.这是我的全部代码。

import pandas as pd
import json
import plotly.express as px

states = pd.read_csv('https://raw.githubusercontent.com/ngpsu22/Child-Poverty-State-Map/master/poverty_rate_map.csv')

us_states = pd.read_json('https://github.com/ngpsu22/Child-Poverty-State-Map/raw/master/gz_2010_us_040_00_500k.json')

state_id_map = {}
for feature in us_states['features']:
  feature['id'] = feature['properties']['NAME']
  state_id_map[feature['properties']['STATE']] = feature['id']

states['id'] = states['state'].apply(lambda x: state_id_map[x])

But I get this error: KeyError: 'Maine' Which since Maine is first in my data frame means that something is going wrong.但我收到此错误:KeyError: 'Maine' 由于缅因州在我的数据框中排在第一位,这意味着出现了问题。

Any suggestions?有什么建议么?

  • us_states.features is a dict us_states.features是一个dict
  • Use pd.json_normalize to extract the dict into a dataframe.使用pd.json_normalizedict提取到 dataframe。
  • 'geometry.coordinates' for each row is a large nested list每行'geometry.coordinates'是一个大的嵌套列表
  • It's not clear what the loop is supposed to do, the data from the two dataframes can be joined together for easier access, using pd.merge .目前尚不清楚循环应该做什么,可以使用pd.merge将来自两个数据帧的数据连接在一起以便于访问。
us_states = pd.read_json('https://github.com/ngpsu22/Child-Poverty-State-Map/raw/master/gz_2010_us_040_00_500k.json')

# convert the dict to dataframe
us_states_features = pd.json_normalize(us_states.features, sep='_')

# the Name column is addressed with
us_states_features['properties_Name']

# join the two dataframe into one
df = pd.merge(states, us_states_features, left_on='state', right_on='properties_NAME')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM