【发布时间】:2021-08-08 22:06:18
【问题描述】:
我目前正在处理几个数据帧,其中一些数据帧的行数超过 300 万行,但为简单起见,我们假设我有这个 df:
import pandas as pd
import numpy as np
df = pd.DataFrame({'a' : np.random.randint(1, 100, 100),
'b' : np.random.randint(1, 300, 100),
'c' : np.random.randint(1, 500, 100),
'id': np.random.randint(1, 11, 100),})
还有 df2:
df2 = pd.DataFrame({'id': np.arange(1, 11),
'd' : np.random.randint(1, 100, 10),
'e' : np.random.randint(1, 200, 10),
'f' : np.random.randint(1, 300, 10),
'g' : np.random.randint(1, 400, 10),
'h' : np.random.randint(1, 500, 10)})
我想要的是通过公共列“id”将 df 和 df2 结合起来。问题是,当我使用 Google Colab 时,会话在合并 RAM 过度使用的数据帧时不断崩溃。这通常不会发生,但 RAM 的过度使用可能是由于我正在处理的数据大小所致
因此,我正在寻找更好的选择;到目前为止,我已经尝试过这些代码:
df = pd.merge(df, df2, on= 'id', how= 'outer')
df = df.set_index('id')
df2 = df2.set_index('id')
df = df.join(df2, how='outer')
df = df.reset_index()
# Session crashes upon resetting index
for c in df2.columns[1:]:
df[c] = df['id'].map(df2.set_index('id')[c])
# Works, but takes considerably long
请指教
【问题讨论】:
-
分块加载数据帧。比如说 100 万行或更少。
标签: python pandas dataframe join merge