具有巨大数据帧的内部联接(约200万列)

2024-07-01 07:07:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据每个数据帧中一列(称为“Names”)中的匹配值连接两个数据帧(df1df2)。我使用R的inner_join函数和Python的pandasmerge函数尝试了这一点,并且能够让这两个函数都成功地在较小的数据子集上工作。我想我的问题是数据帧的大小。在

我的数据帧如下:

  • df1有“Names”列和5个附加列,并且有大约900行。在
  • df2有“Names”列,还有~200万个附加列,还有~900行。在

我试过(在R):

df3 <- inner_join(x = df1, y = df2, by = 'Name') 

我也尝试过(在Python中,df1和{}是Pandas数据帧):

^{pr2}$

(其中'Name'列位于df1的索引1和df2的索引0处)

当我将上述方法应用于我的完整数据帧时,它会运行很长时间,最终会崩溃。另外,我怀疑问题可能出在我的df2中的200万列,因此我尝试将其(按行)细分为更小的数据帧。我的计划是将df2的小子集与df1连接起来,然后在最后将新的数据帧行绑定在一起。{cd2>加入更小的cd2}也不成功。在

如果有人能提供任何建议,我将不胜感激。在


Tags: 数据函数namepandasbynames子集inner
2条回答

谢谢大家的帮助!使用数据表正如@shadowtalker建议的那样,极大地加快了这个过程。仅供参考,以防有人试图做类似的事情,df1大约是400MB,我的df2文件大约是3gb。在

我完成了以下任务:

library(data.table)
df1 <- setDT(df1)
df2 <- setDT(df2)
setkey(df1, Name)
setkey(df2, Name)
df3 <- df1[df2, nomatch = 0]

这是一个非常难看的解决方法,我将df2的列分解并逐个添加它们。不确定它是否有效,但可能值得一试:

# First, I only grab the "Name" column from df2
df3 = df1.merge(right=df2[["Name"]], how="inner", on="Name")  

# Then I save all the column headers (excluding 
# the "Name" column) in a separate list
df2_columns = df2.columns[np.logical_not(df2.columns.isin(["Name"]))]

# This determines how many columns are going to get added each time.
num_cols_per_loop = 1000

# And this just calculates how many times you'll need to go through the loop
# given the number of columns you set to get added each loop
num_loops = int(len(df2_columns)/num_cols_per_loop) + 1

for i in range(num_loops):
    # For each run of the loop, we determine which rows will get added
    this_column_sublist = df2_columns[i*num_cols_per_loop : (i+1)*num_cols_per_loop]

    # You also need to add the "Name" column to make sure 
    # you get the observations in the right order
    this_column_sublist = np.append("Name",this_column_sublist)

    # Finally, merge with just the subset of df2
    df3 = df3.merge(right=df2[this_column_sublist], how="inner", on="Name")

就像我说的,这是一个丑陋的解决办法,但可能会奏效。在

相关问题 更多 >

    热门问题