【问题标题】:Python: Alternative to Panda's merge()Python:替代 Panda 的 merge()
【发布时间】: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


【解决方案1】:

或者你可以这样做:

首先将两个df的'id'列作为它们的索引:

df=df.set_index('id')
df2=df2.set_index('id')

最后使用 isin() 方法创建一个布尔掩码,检查 df 的索引是否在 df2 的索引中,并将该掩码传递给 df 并使用 assign() 方法赋值:

df=df[df.index.isin(df2.index)].assign(d=df2['d'],e=df2['e'],f=df2['f'],g=df2['g'],h=df2['h'])

如果需要使用reset_index() 方法:

df=df.reset_index()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2019-04-05
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2019-03-06
    相关资源
    最近更新 更多