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

alw*_*ous 5 python dataframe pandas

给定这两个数据框,如何获得预期的输出数据框?很长的路要走,用循环遍历数据框的行,iloc然后map在转换df2为a 之后使用该函数将dictx和y映射到它们的分数。

这似乎很乏味,并且需要花费很长时间才能在大型数据帧上运行。我希望有一个更清洁的解决方案。

df1:

ID    A    B    C
1     x    x    y
2     y    x    y
3     x    y    y
Run Code Online (Sandbox Code Playgroud)

df2:

ID    score_x    score_y
1          20         30
2          15         17
3          18         22
Run Code Online (Sandbox Code Playgroud)

输出:

ID    A     B     C
1     20    20    30
2     17    15    17
3     18    22    22
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

San*_*apa 8

使用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
Run Code Online (Sandbox Code Playgroud)
print(df2)
     x   y
ID        
1   20  30
2   15  17
3   18  22
Run Code Online (Sandbox Code Playgroud)


Ste*_*tef 4

使用面膜

df1.set_index('ID', inplace=True)
df2.set_index('ID', inplace=True)

df1.mask(df1=='x',df2['score_x'],axis=0).mask(df1=='y',df2['score_y'],axis=0)
Run Code Online (Sandbox Code Playgroud)

结果:

     A   B   C
ID            
1   20  20  30
2   17  15  17
3   18  22  22
Run Code Online (Sandbox Code Playgroud)

如果有很多列并且它们都以相同的方式命名,您可以使用类似的内容:

for e in df2.columns.str.split('_').str[-1]:
     df1.mask(df1==e, df2['score_'+e], axis=0, inplace=True)
Run Code Online (Sandbox Code Playgroud)