python - 如何在Python数据框中添加带有字典字符串值的列
问题描述
我正在尝试添加一个包含字典值的列。
DataFrame 如下所示,共有 29 个国家的 数据框截图
我的字典如下所示:
# Define a dictionary containing european Regions
eu_regions = {'Central and Eastern Europe': ['Latvia', 'Bulgaria', 'Lithuania', 'Croatia', 'Czechia','Poland','Romania', 'Slovakia', 'Slovenia', 'Hungary'],
'Northern Europe': ['Sweden', 'Norway', 'Denmark', 'Finland', 'Estonia'],
'Western Europe': ['Austria', 'Belgium', 'Luxembourg', 'Netherlands', 'France', 'Germany', 'Ireland', 'Norway', 'United Kingdom'],
'Southern Europe': ['Italy', 'Cyprus','Malta', 'Portugal', 'Greece', 'Spain']}
添加名为“区域”的新列,这意味着添加我使用以下命令的每个国家/地区的区域。
eu_vaccine_df['region'] = eu_vaccine_df['country'].map(eu_regions)
eu_vaccine_df.head()
然而,在结果中,创建了新列“区域”,但没有添加新国家,也无法将国家与字典的区域匹配。
解决方案
这有帮助吗?
country_dct = {}
for key, countries in eu_regions.items():
for country in countries:
country_dct[country] = key
eu_vaccine_df['region'] = eu_vaccine_df['country'].map(country_dct)
eu_vaccine_df.head()
推荐阅读
- javascript - 显示一个
- python - Keras:输入张量的等级必须为 3、4 或 5,但为 2
- logic - 转换系统和计算树逻辑 - 无法理解这一点
- javascript - (Jquery Validate) onkeyup: false 适用于一个字段,直到我第二次选择它
- c# - 如何使用 OpenXmlAttribute 更改字体大小?
- algorithm - 子串部分数量受限的最长公共子序列
- javascript - 如何使用纯javascript从spritesheet中提取精灵
- javascript - 将 Input 标签值发送到 React.js 中的另一个组件
- google-cloud-firestore - 我想做一个 Tinder 替代品。我认为我的匹配机制会占用太多的数据库空间。如何改进它?
- postman - 邮递员:请求失败,CORS:ORIGIN_NOT_ALLOWED