如何将一个数据框的单列中的值映射到另一个数据框的两列并提取映射的值?

时间:2020-09-08 07:05:24

标签: python pandas

我有两个数据帧

df1 = pd.read_excel("data1.xlsx")
df2 = pd.read_excel("data2.xlsx"

df1

Data1   Data2   Score
ABC      AB1    1
AB1      ABC    4
AB2      AB2    6
ABC      ABD    0.7
GDH      ABD    0.9
KMN      KSF    0.5
KSF      KSF    6

df2

Data1
AB1
AB2
ABC

我想将df2["Data1"]映射到df1并提取映射值:

merged_data = pd.merge(df2, df1, how='inner', left_on='Data1', right_on='Data1')
merged_data2 = pd.merge(df2, df1, how='inner', left_on='Data1', right_on='Data2')

combined_data = pd.concat([merged_data,merged_data2])
#remove duplicates
combined_data_rm = combined_data.drop_duplicates()
combined_data_rm

Data1   Data2   Score
ABC      AB1    1
AB1      ABC    4
AB2      AB2    6
ABC      ABD    0.7

使用熊猫分析还有其他方法吗?

1 个答案:

答案 0 :(得分:2)

尝试一下

print(pd.merge(df1, df2, on=["Data1"]))

O / P:

  Data1 Data2  Score
0   ABC   AB1    1.0
1   ABC   ABD    0.7
2   AB1   ABC    4.0
3   AB2   AB2    6.0