python - 将外键从一个数据帧附加到另一个数据帧的最快方法
问题描述
这让我很沮丧,因为我确信这很容易做到,但我终其一生都无法提出最佳解决方案。
基本上假设我有df1
,它有列vehicle
,checkpoint
,代表比赛中每辆车在单圈中通过每个检查点的时间。但是没有记录同一场比赛的某些检查站。
然后我有df2
其中包含一个包含检查点数据的单列checkpoint
,这些数据应该包含在df1
.
我试图找到一种快速的方法来将这些检查点添加lap
到df1
.
例如:
df1 = pd.DataFrame({'vehicle': [1,1,2,2,3,3], 'checkpoint': [1,5,1,5,1,5]}) df2 = pd.DataFrame({"checkpoints": range(2,5)})
我想要的是快速生成一个数据框,将所有 df2 缺失的检查点添加到 df1 中的每辆车,以便生成的数据框对于 3 辆独特的车辆中的每一辆都有检查点 1 到 5。
预期输出如下所示,但检查站和车辆不一定要按顺序排列。重要的是所有 5 个检查点都包含在所有 3 辆车中:
vehicle checkpoints
0 1 1
1 1 2
2 1 3
3 1 4
4 1 5
5 2 1
6 2 2
7 2 3
8 2 4
9 2 5
10 3 1
11 3 2
12 3 3
13 3 4
14 3 5
I've come up with solutions using list comprehensions and concatenation but it's far too slow on larger datasets. I'm not the most at ease with using apply either, so if there's a way to use apply or an entirely different and faster solution, I would be very much appreciative.
If you need more information don't hesitate to ask.
解决方案
import pandas as pd
df1 = pd.DataFrame({'vehicle': [1,1,2,2,3,3], 'checkpoint': [1,5,1,5,1,5]})
df2 = pd.DataFrame({"checkpoint": range(2,5)})
merge
基于解决方案
连接df1
和完全外部合并来自df1
和缺少检查点的独特车辆df2
:
pd.concat([df1,
pd.merge(df1[['vehicle']].drop_duplicates().assign(temp=1),
df2.assign(temp=1), how='outer').drop('temp', axis=1)]
).sort_values(['vehicle', 'checkpoint']).reset_index(drop=True)
输出如 OP 所示。
reindex
基于解决方案
import itertools
all_vehicles = df1.vehicle.unique().tolist()
all_checkpoints = (df1.checkpoint.unique().tolist()
+ df2.checkpoint.unique().tolist())
(df1.set_index(['vehicle', 'checkpoint'])
.reindex(index=itertools.product(all_vehicles, all_checkpoints))
.reset_index())
推荐阅读
- python - 将 PyPDF2 和 pdftotext 与 Spyder 一起使用
- mysql - 如何在 mySQL 工作台中刷新 csv 数据表
- apache-nifi - Apache NiFi:如何运行预定处理器来删除使用通配符指定的文件?
- java - 从反应堆通量返回的错误变得无限
- node.js - 使用 OpenSSL 在应用程序级别实现双向 TLS
- python - 如何在不创建列名的每个时间行的情况下将键和值附加到数据框?
- bash - 如何在Bash中逐字写入文件斜线分割字符串
- html - 如何更改悬停div上方的兄弟div的样式
- sql - 具有连接值的 SQL 查询。如何合并重复并添加标识符?
- python - 使用win32gui抓拍灰度画面