df1
1A 1B 1C
a1 b1 c1
a2 b2 c2
a3 b3 c4
df2
ID
a1
b1
c4
a3
我想用 df 匹配的列名称标记 df2 中的每一行。
期望的输出
ID ID_name
a1 1A
b1 1B
c4 1C
a3 1A
a8 NaN
这些是我的代码,它可以满足我的要求,
save_p = []
for ix,row1 in df2.iterrows():
for ix2, row2 in df1.iterrows():
if row1.1A == row2.ID:
save_p.append((row2.ID,'1A'))
if row1.1B == row2.ID:
save_p.append((row2.ID,'1B'))
if row1.1C == row2.ID:
save_p.append((row2.ID,'1C'))
......等等 但我想要一些最好/优雅的方法?谢谢。
最佳答案
使用Series.map
与 DataFrame.melt
,如果没有匹配则获取缺失值,例如 c3
,因为 df1
中没有:
s = df1.melt().set_index('value')['variable']
#if possible duplicates remove them
#s = df1.melt().drop_duplicates('value').set_index('value')['variable']
df2['ID_name'] = df2['ID'].map(s)
print (df2)
ID ID_name
0 a1 1A
1 b1 1B
2 c4 1C
3 c3 NaN
详细信息:
print (df1.melt())
variable value
0 1A a1
1 1A a2
2 1A a3
3 1B b1
4 1B b2
5 1B b3
6 1C c1
7 1C c2
8 1C c4
关于python - 将两个 df 和 tag 与列名匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57476549/