Python中大Pandas合并的MemoryError

2024-04-18 17:46:36 发布

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

我使用pandas对大约1000-2000个CSV文件进行outer合并。每个CSV文件都有一个标识符列id,它在所有CSV文件之间共享,但是每个文件都有一组3-5列的唯一列。每个文件中大约有20000个唯一的id行。我要做的就是将这些合并在一起,将所有新列合并在一起,并使用id列作为合并索引。在

我使用一个简单的merge调用来完成:

merged_df = first_df # first csv file dataframe
for next_filename in filenames:
   # load up the next df
   # ...
   merged_df = merged_df.merge(next_df, on=["id"], how="outer")

问题是,对于将近2000个CSV文件,pandas抛出的merge操作中有一个MemoryError。我不确定这是否是由于合并操作中的问题造成的限制?在

最终的数据帧将有20000行,大约(2000x3)=6000列。这是很大的,但不够大,以消耗所有的内存,我正在使用的计算机有超过20 GB的RAM。这个尺寸对熊猫来说太大了吗?我应该使用类似sqlite的东西吗?在merge操作中有什么我可以改变的地方,使它在这个范围内工作吗?在

谢谢。在


Tags: 文件csviddataframepandasdffor标识符
3条回答

{我认为使用外部连接可以获得更好的性能:

dfs = (pd.read_csv(filename).set_index('id') for filename in filenames)
merged_df = pd.concat(dfs, axis=1)

这意味着您只对每个文件执行一个合并操作,而不是执行一个合并操作。

我在使用带有1GB文件的read_csv时在32位pyt中遇到了相同的错误。 尝试64位版本,希望能解决内存错误问题

pd.concat对于大数据帧似乎内存不足,一种选择是将dfs转换为矩阵并将其合并。在

def concat_df_by_np(df1,df2):
    """
    accepts two dataframes, converts each to a matrix, concats them horizontally and
    uses the index of the first dataframe. This is not a concat by index but simply by
    position, therefore the index of both dataframes should be the same
    """
    dfout = deepcopy(pd.DataFrame(np.concatenate( (df1.as_matrix(),df2.as_matrix()),axis=1),
                                  index   = df1.index, 
                                  columns = np.concatenate([df1.columns,df2.columns])))
    if (df1.index!=df2.index).any():
       #logging.warning('Indices in concat_df_by_np are not the same')                     
       print ('Indices in concat_df_by_np are not the same')                     


    return dfout

但是,需要小心,因为这个函数不是一个连接,而是一个水平附加,而索引被忽略

相关问题 更多 >