我正在设法找到一个解决我问题的好办法。我有三张桌子:
Code DF
Code1 Code2 Code3 Code4 Code5
Eur xxx xxx xxx xxx
xxx xxx xxx ESP xxx
ASI xxx xxx xxx xxx
xxx BRA xxx xxx xxx
xxx AUS xxx xxx xxx
xxx xxx NOR xxx xxx
xxx xxx xxx PRT xxx
xxx xxx xxx xxx SGP
Country1 DF
Country-Code Region
Eur Europe
ASI Asia
BRA America
AUS Asia
NOR Europe
Country2 DF
Country Code Region
ESP Europe
PRT Europe
SGP Asia
ASI Asia
所以我想做的是,创建第五列地区。第一我想分别检查Code5和Code4中的值,如果其中一个代码与Country2 dataframe匹配,那么将其对应的Region值放在Region列中。如果在Code5中没有找到匹配的代码,则转到Code4,如果没有代码3等。Code5缩写和Code4需要查找Country2数据帧和Code3,Code2和Code1需要查找Country1数据帧。为了澄清“xxx”可以是其他3个字母的缩写,也可以是空白。Country1 DF和Country2 DF之间也可能存在相似的代码和区域,但是Code4和Code5有一些值不应该与Country1 DF匹配,这就是为什么要匹配两个不同的数据帧。这里的例子是欧元,在代码1,代码2,代码3是欧洲地区,但在代码4,代码5中,它是货币,我不希望它映射到欧洲,如果它包含在这两列中的一列。 最终情况需要如下所示:
^{pr2}$
存储国家代码映射的更好方法是在字典中。我假设
country_dict1
,country_dict2
分别是每个数据帧的code:region
的映射:您可以使用列表理解来完成此操作:
其他资源
Appending Column to Pandas DF
List Comprehensions
Sets and Operations with Sets
相关问题 更多 >
编程相关推荐