我有两个pandas数据帧,其中一个更新了主数据帧的值的子集。主要的行是~2m行,要更新的列是~20k。这个操作运行得非常慢,因为我把它放在下面,据我所知,它的运行速度是O(m*n),有没有一个很好的方法来向量化它,或者只是一般地提高速度?我看不出有多少其他的优化可以应用于这种情况。我也尝试过将“object_id”列作为索引,但这并没有带来明显的速度提升。
# df_primary this is 2m rows
# df_updated this is 20k rows
for idx, row in df_updated.iterrows():
df_primary.loc[df_primary.object_id == row.object_id, ['status', 'category']] = [row.status, row.category]发布于 2020-10-12 10:32:55
让我们使用来自df_updated的值来尝试使用DataFrame.update就地更新df_primary
df_primary = df_primary.set_index('object_id')
df_primary.update(df_updated.set_index('object_id')[['status', 'category']])
df_primary = df_primary.reset_index()发布于 2020-10-12 10:01:20
根据需要使用连接方法,比如左/右/内连接。它将会比其他任何方式都要快。
https://stackoverflow.com/questions/64310484
复制相似问题