gpt4 book ai didi

python - 如何将一个数据框映射到另一个数据框(python pandas)?

转载 作者:太空狗 更新时间:2023-10-30 00:30:51 25 4
gpt4 key购买 nike

给定这两个数据帧,我如何获得预期的输出数据帧?较长的方法是使用 iloc 循环遍历数据帧的行,然后在将 df2 转换为 后使用 map 函数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

输出:

ID    A     B     C
1 20 20 30
2 17 15 17
3 18 22 22

注意:数据框会有很多列,并且不仅仅是 x 和 y 作为类别(可能在 20 个类别的区域中)。

谢谢!

最佳答案

使用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

关于python - 如何将一个数据框映射到另一个数据框(python pandas)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com