python-3.x - 来自具有不同列名和行大小但几乎没有重合值的两个数据帧的结果数据帧,并行呈现(Python)
问题描述
有两个数据框,其中包含玩家 ID 和他们在两天的锦标赛(周一和周五)中获得的所有积分。我想得到一个具有以下格式的最终数据框。
final =
match_monday points match_friday points
0 player#0005 13.0 player#0005 19.0
1 player#0067 26.0 player#0067 0.0
2 player#0098 0.0 player#0098 23.0
4 player#0104 24.0 player#0104 0.0
5 player#0211 14.0 player#0211 0.0
6 player#0227 17.0 player#0227 21.0
起点是这两个数据框:
df1 =
match_monday points
0 player#0227 17.0
1 player#0005 13.0
2 player#0104 24.0
3 player#0067 26.0
4 player#0211 14.0
df2 =
match_friday points
0 player#0227 21.0
1 player#0098 23.0
2 player#0005 19.0
#Dataframes scripts:
df1 = pd.DataFrame([['player#0227',17.0],['player#0005',13.0],['player#0104',24.0],['player#0067',26.0],['player#0211',14.0]],columns=['match_monday','points'])
df2 = pd.DataFrame([['player#0227',21.0],['player#0098',23.0],['player#0005',19.0]],columns=['match_friday','points'])
我已经合并了这两个数据框,并意识到从这里开始我需要很多步骤才能达到所需的格式。合并结果:
match_monday points match_friday
0 player#0227 17.0 NaN
1 player#0005 13.0 NaN
2 player#0104 24.0 NaN
3 player#0067 26.0 NaN
4 player#0211 14.0 NaN
5 NaN 21.0 player#0227
6 NaN 23.0 player#0098
7 NaN 19.0 player#0005
当我意识到我的方法不是那么好时,我试图用这句话命令 match_friday 放入一个“for循环”。
matchMon = df2[df2.match_friday.isin(df1.match_monday)]
print(machMon)
match_friday points
0 player#0227 21.0
2 player#0005 19.0
解决方案
我认为更好的是使用不同的方法 -Series
通过DataFrame.set_index
with创建concat
并最后替换缺失值fillna
- 然后获取所有玩家的索引:
a = df1.set_index('match_monday')['points'].rename('po_mon')
b = df2.set_index('match_friday')['points'].rename('po_fri')
df = pd.concat([a, b], axis=1, sort=False).fillna(0)
print (df)
po_mon po_fri
player#0227 17.0 21.0
player#0005 13.0 19.0
player#0104 24.0 0.0
player#0067 26.0 0.0
player#0211 14.0 0.0
player#0098 0.0 23.0
推荐阅读
- regex - 在具有特定值的字符串中查找“~XX~”
- snowflake-cloud-data-platform - Snowflake Windows Analytical Function to set grouping set
- prolog - 从满足特定条件的列表中删除/更新所有列表
- python - TensorFlow 在循环中减速
- networking - ECS EC2 实例需要私有并连接到 ECS 端点以进行容器互联网访问
- amazon-web-services - 如何部分执行 Terraform 代码?
- c++ - “错误:在转换的常量表达式中不允许从'double'转换为'std :: size_t'(又名'unsigned long')”是什么意思?
- python - 从列表中消除嵌套的空列表
- azure - Azure 函数从 Azure 应用配置配置计时器触发器
- javascript - 如何在组件内的组件中启用 Scrollview