Pandas通过将dataframe列与其他多个列相匹配来生成一个列

2024-09-26 22:54:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在设法找到一个解决我问题的好办法。我有三张桌子:

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}$

Tags: 数据代码dfcoderegionxxxeuropeasi
2条回答

存储国家代码映射的更好方法是在字典中。我假设country_dict1country_dict2分别是每个数据帧的code:region的映射:

def determine_region(row):
    for item in row[:-3:-1]:
        if item in country_dict1:
            return country_dict1.get(item)
    for item2 in row[-3::-1]:
        if item2 in country_dict2:
            return country_dict2.get(item2)
    return pd.np.nan

df['Region'] = df.apply(determine_region, axis=1)

您可以使用列表理解来完成此操作:

def determine_region(df_row):
    # if else chain to make a decision for each row
    # or maybe you could use python builtin set to make it 
    # more semantic

# capture each item into a list with a comprehension
x = [ determine_region(x) for x in CodeDF ]
# append the data into a new column named region
CodeDF.loc[:,'Region'] = pd.Series(x)

其他资源

Appending Column to Pandas DF

List Comprehensions

Sets and Operations with Sets

相关问题 更多 >

    热门问题