我的字典中有 3750 个数据框,每个数据框有 500-550 行,如果我们合并它们,总计可达 180 万条记录。
我希望将字典中的 3750 个数据帧合并/连接到一个包含 180 万到 190 万条记录的大型 pandas 数据帧中。
目前,我的代码需要永远运行,而且我确信根本效率不高:(我也尝试对其中一列进行索引以提高效率,但它没有帮助)。
# pdf_dict is the pandas dictionary with 3750 dataframes
# convert your dictionary to a list
list_dataframes = pdf_dict.values()
# keep the dictionary keys with the same order, in case you will need them
list_dataframes_keys = pdf_dict.keys()
# if the date is not the index
df = pd.concat([x.set_index('order_date') for x in list_dataframes], axis=1)
# if the date is the index
df = pd.concat([x for x in list_dataframes], axis=1)
也不确定“concat”函数对于数据大小是否足够有效。
df = pd.concat(pd_dct.values())
示例词典如下:
import pandas as pd
df1 = pd.DataFrame({
"col1":['val1','val3'],
"col2":['val2','val3'],
"col3":['val3','val5']
})
df2 = pd.DataFrame({
"col1":['val7','val3'],
"col2":['val2','val3'],
"col3":['val3','val5']
})
df3 = pd.DataFrame({
"col1":['val10','val3'],
"col2":['val12','val3'],
"col3":['val13','val5']
})
pd_dct = {"A": df1, "B": df2, "C": df3}
任何指导都非常有价值,请帮忙。
感谢您提前抽出时间。
试试这个:
pd.concat(pd_dct.values(),ignore_index=True)