我正在使用pandas对一组大约1000-2000个CSV文件进行outer
合并。每个CSV文件都有一个标识符列id
,它在所有CSV文件之间共享,但是每个文件都有一组3-5列的唯一列。每个文件中大约有20,000个唯一的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文件,我在熊猫抛出的merge
操作中得到MemoryError
。我不确定这是否是由于合并操作中的问题而造成的限制?
最终的数据帧将有20,000行和大约(2000 x 3) = 6000列。这是很大的,但不足以消耗我使用的计算机上的所有内存,它有超过20 GB的RAM。这个尺寸对熊猫来说是不是太大了?我应该使用sqlite之类的东西吗?我可以在merge
操作中改变一些东西以使其在这种规模上工作吗?
谢谢。
我认为使用concat
(其作用类似于外部连接)会获得更好的性能:
dfs = (pd.read_csv(filename).set_index('id') for filename in filenames)
merged_df = pd.concat(dfs, axis=1)
这意味着您只做一个合并操作,而不是每个文件一个。
我在32位pyt中使用1GB文件的read_csv时遇到了相同的错误。尝试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
然而,需要注意的是,这个函数不是一个连接,而是一个水平追加,而其中的索引被忽略