python - 映射字典与大陆 : Country to a DataFrame with a Country Column

标签 python pandas dataframe

我有一个包含 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/

相关文章:

python - Pandas.to_datetime 函数静默失败

python - 使用具有混合类型列的 rpy2 将 pandas df 转换为 R data.frame

r - 按组选择具有最小值的行

python - 哪些类型的语言允许以编程方式创建变量名?

python - 选择与键对应的字典值

python - pandas.DataFrame.equals 的古怪行为

python - 将数据框列与条件进行比较

python - 使用两列连接,从四个其他数据帧填充一个 pandas 数据帧中的列

python - 根据文件名的一部分合并文件

Python:将打印函数作为参数发送