python - How to map one dataframe to another (python pandas)?
问题描述
Given these two dataframes, how do I get the intended output dataframe?
The long way would be to loop through the rows of the dataframe with iloc
and then use the map
function after converting df2
to a dict
to map the x and y to their score.
This seems tedious and would take long to run on a large dataframe. I'm hoping there's a cleaner solution.
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
Note: the dataframes would have many columns and there would be more than just x and y as categories (possibly in the region of 20 categories).
Thanks!
解决方案
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
推荐阅读
- firebase - Flutter firebase-admob 检查奖励视频是否正在加载
- sql - 转换特定的纪元时间
- javascript - 是否有适用于本地 IP 地址的代理服务器替代方案来绕过 CORS?
- python-2.7 - 从 Google Cloud Storage 存储分区进行 pip 安装
- azure - Azure 市场:是否可以在托管应用程序优惠中使用图像?
- java - 在类中使用 Piamge 处理(java)
- node.js - Apollo 客户端:未定义变量。收到状态码 400
- java - 如何在返回整个(修改后的)字符串的同时用 replaceAll() 替换捕获组?
- eclipse - STS-添加服务器-当我尝试添加 oracle weblogic 服务器时,下一步按钮被禁用
- c - 在 C 中通过 UDP 在结构中发送动态数组