给定这两个数据帧,如何获得预期的输出数据帧?
长的方法是循环遍历数据帧的行iloc
然后使用map
转换后的函数df2
to a dict
将 x 和 y 映射到它们的分数。
这看起来很乏味,并且在大型数据帧上运行需要很长时间。我希望有一个更清洁的解决方案。
df1:
ID A B C
1 x x y
2 y x y
3 x y y
df2:
ID score_x score_y
1 20 30
2 15 17
3 18 22
output:
ID A B C
1 20 20 30
2 17 15 17
3 18 22 22
注意:数据框将有许多列,并且不仅仅是 x 和 y 作为类别(可能在 20 个类别的区域中)。
Thanks!
Use DataFrame.apply沿着列Series.map:
df1.set_index('ID', inplace=True)
df2.set_index('ID', inplace=True)
df2.columns = df2.columns.str.split('_').str[-1]
df1 = df1.apply(lambda x: x.map(df2.loc[x.name]), axis=1).reset_index()
print(df1)
ID A B C
0 1 20 20 30
1 2 17 15 17
2 3 18 22 22
print(df2)
x y
ID
1 20 30
2 15 17
3 18 22
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)