【问题标题】:How to Create id for Mapping with plotly.express如何使用 plotly.express 为映射创建 id
【发布时间】:2020-11-23 03:25:12
【问题描述】:

我有一个数据框“states”,其中包含每个州的儿童贫困率和名为“us_states”的 json 文件。我想使用 plotly express 创建一个等值线图,但我正在努力创建 id 列。这是我的全部代码。

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])

但我收到此错误: KeyError:'缅因州' 由于缅因州在我的数据框中排在第一位,这意味着出现了问题。

有什么建议吗?

【问题讨论】:

    标签: python pandas plotly json-normalize


    【解决方案1】:
    • us_states.featuresdict
    • 使用pd.json_normalizedict 提取到数据帧中。
    • 'geometry.coordinates' 每一行都是一个大的嵌套列表
    • 不清楚循环应该做什么,来自两个数据帧的数据可以连接在一起以便于访问,使用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')
    

    【讨论】:

    • 是的,我想我明白了,但我遇到了新的错误。我认为 plotly 会让这更简单。 TypeError: 字符串索引必须是整数
    • @NateGo 使用更新的代码和整个 Traceback 作为文本打开一个新问题。当你得到它时在这里评论,我会看看
    猜你喜欢
    • 1970-01-01
    • 2019-09-24
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2011-12-08
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多