我有一个包含 df['Country'] 列的数据框。我创建了一个字典,其中所有大陆作为键,值作为相应国家/地区的列表。
大陆 = { "北美": ["加拿大","墨西哥","美国"]}
我想将其映射到我的数据框中,它会在其中创建一个列,其中包含 df['Country'] 对应大陆中的每个值。
我已尝试以下操作,但它返回一列 NA 值
df['大陆'] = df['国家'].map(大陆)
我需要创建一个函数来绘制大陆 map 吗?或者我可以使用 pandas .map() 方法吗?
最佳答案
您的词典格式错误,您需要相反的格式(并且没有列表)。
您可以使用它来获取正确的格式:
countries_map = {country: continent
for continent,countries in continents.items()
for country in countries}
输出:
{'Canada': 'North America',
'Mexico': 'North America',
'United States': 'North America'}
然后继续:
df['Continents'] = df['Country'].map(countries_map)
关于python - 映射字典与大陆 : Country to a DataFrame with a Country Column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68943476/