[英]Add a column to Pandas DataFrame with multiple lookups based on other columns
[英]Pandas generates a column based by matching the dataframe columns to multiple other columns
我正在尝试找到解决问题的巧妙方法。 我有三个表:
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
所以我想做的是,创建一个第五列作为Region.First我想分别检查Code5和Code4中的值,如果其中一个代码与Country2数据帧匹配,然后将其对应的Region值放入Region列中。 如果在Code5中找不到匹配的代码,请转到Code4,如果没有,则在Code3等中找到。Code5的缩写和Code4需要在Country2数据框中查找,而Code3,Code2和Code1则需要在Country1数据框中查找。 只是为了澄清“ xxx”,可以是其他3个字母的缩写或空白。 在Country1 DF和Country2 DF之间可能也有类似的Code和Region,但是有些值Code4和Code5不应与Country1 df匹配,这就是为什么要使用两个不同的数据帧进行匹配的原因。 这里的情况是EUR,在Code1,Code2,Code3中是欧洲区域,但是在Code4,Code5中是货币,如果它包含在这两列之一中,则我不希望它映射到欧洲。 最终案例方案必须是这样的:
`Code1 Code2 Code3 Code4 Code5 Region
Eur xxx xxx xxx xxx Europe
xxx xxx xxx ESP xxx Europe
ASI xxx xxx xxx xxx Asia
xxx BRA xxx xxx xxx America
xxx AUS xxx xxx xxx Asia
xxx xxx NOR xxx xxx Europe
xxx xxx xxx PRT xxx Europe
xxx xxx xxx xxx SGP Europe
`
您可以通过列表理解来做到这一点:
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)
其他资源
存储国家代码映射的更好方法是在字典中。 我将假设country_dict1
和country_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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.