[英]Merge two data frames by matching one column from the first data frame with two columns from the second data frame
I'm working with two data frames:我正在使用两个数据框:
df1 = {'Metropolitan area': {0: 'New York City',
1: 'Los Angeles',
2: 'San Francisco Bay Area',
3: 'Chicago',
4: 'Dallas–Fort Worth'},
'token_nhl': {0: 'Devils',
1: 'Ducks',
2: 'Sharks',
3: 'Blackhawks',
4: 'Stars'}}
df2 = {'NHL': {0: 'team1', 1: 'team2', 2: 'team3', 3: 'team4', 4: 'team5'},
'token_nhl': {0: 'Devils', 1: 'Ducks', 2: 'x', 3: 'Stars', 4: 'Sharks'},
'token_nhl1': {0: 'a', 1: 'b', 2: 'Blackhawks', 3: 'c', 4: 'd'}}
I'm trying to merge them, but I'd like to match the values of the 'token_nhl' columns in df1 with both 'token_nhl' and 'token_nhl1' in df2, so whenever I don't find a value in 'token_nhl', I go look for it in 'token_nhl1',and then the resulting data frame would be:我正在尝试合并它们,但我想将 df1 中的“token_nhl”列的值与 df2 中的“token_nhl”和“token_nhl1”相匹配,所以每当我在“token_nhl”中找不到值时, 我 go 在 'token_nhl1' 中寻找它,然后得到的数据帧将是:
{'NHL': {0: 'team1', 1: 'team2', 2: 'team3', 3: 'team4', 4: 'team5'},
'token_nhl_left': {0: 'Devils', 1: 'Ducks', 2: 'x', 3: 'Stars', 4: 'Sharks'},
'token_nhl1_left': {0: 'a', 1: 'b', 2: 'Blackhawks', 3: 'c', 4: 'd'},
'token_nhl_right': {0: 'Devils',1: 'Ducks',2: 'Blackhawks',3: 'Stars',4: 'Sharks'}}
For this you need to merge two times:为此,您需要合并两次:
1: renaming columns, becuase after merge pandas is not giving two different columns 1:重命名列,因为合并后 pandas 没有给出两个不同的列
df1 = df1.rename(columns = {"token_nhl":"token_nhl_left"})
df2 = df2.rename(columns = {"token_nhl":"token_nhl_right"})
# creating variables
left_on = "token_nhl_left"
right_on1 = "token_nhl_right"
right_on2 = "token_nhl1"
left_columns = df1.columns
merge-1合并1
df_temp1 = pd.merge(left = df1, right = df2, left_on = left_on, right_on = right_on1, how = 'left')
merge-2合并 2
df_temp2 = pd.merge(left = df_temp1[pd.isna(df_temp1[right_on1])][left_columns], right = df2, left_on = left_on, right_on = right_on2, how = 'left')
concat连接
df_final = pd.concat([df_temp1[pd.notna(df_temp1[right_on1])], df_temp2])
My approach to this question involves two steps.我解决这个问题的方法包括两个步骤。
1 - Create a chunk of code to bring the desired information to a list: 1 - 创建一段代码以将所需信息带到列表中:
lis = []
for (y,w) in zip(list(df2['token_nhl']), list(df2['token_nhl1'])):
if y in list(df1['token_nhl']):
lis.append(y)
else:
lis.append(w)
2 - Assign that list to a new data frame with all other needed data. 2 - 将该列表分配给包含所有其他所需数据的新数据框。 After that, rename columns:
之后,重命名列:
df3 = df2.assign(token_nhl_right=lis)
df3.rename(columns={'token_nhl':'token_nhl_left' ,'token_nhl1':'token_nhl1_left'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.