在Pandas中附加大量Excel文件的最快方法

时间:2017-09-25 06:32:11

标签: python python-2.7 pandas pandas-datareader

我有很多excel文件(大约30K),每个文件都有项目属性(一个excel有3K行)。所有excel文件中都存在一些列。此外,还有更多列可能不存在于所有列中。我想将它们合并到一个数据框中。

我尝试使用pandas.read_excel读取每个数据帧,然后通过pandas.append合并它们,这不仅非常慢,而且对某些文件也失败。

使用的代码:

all_data = pd.DataFrame()
dfs = []
for f in glob.glob("sheets_*.xlsx"):
    temp = pd.read_excel(f, sheetname='ItemDetail', skiprows=[0, 2],index_col=0)
    temp = clean_data(temp) # Do some cleaning here.
    dfs.append(temp)

all_data = all_data.append(dfs,ignore_index=True)

示例: -

Excel 1

| Item Id   | Source  | country   | Item Name   |Item Weight   |Cost |
----------------------------------------------------------------------
|   1       |   x     | India     |   Pen       |     10       | 100 |
|   2       |   y     | Australia |   Pencil    |     15       | 50  | 
|   3       |   x     | Germany   |   Eraser    |      5       | 20  |
|   4       |   y     | India     |   Box       |     80       | 200 |
----------------------------------------------------------------------

Excel 2

| Item Id   | Source  | country   | Item Name   |Item Weight   |Length| Width |
|-----------------------------------------------------------------------------|
|   1       |   x     | Australia |   chair     |     100      | 20   |   26  |
|   2       |   y     | Australia |   cupboard  |     150      | 30   |   40  |
|   3       |   x     | Germany   |   Table     |      500     | 60   |   50  |
|   4       |   y     | Germany   |   Tool      |     360      | 20   |   80  |
|-----------------------------------------------------------------------------|

最终合并数据:

| Item Id   | Source  | country   | Item Name   |Item Weight   |Length| Width | Cost |
|------------------------------------------------------------------------------------|
|   10      |   x     | Australia |   chair     |     100      | 20   |   26  |  NAN |
|   26      |   y     | Australia |   cupboard  |     150      | 30   |   40  |  NAN |
|   38      |   x     | Germany   |   Table     |     500      | 60   |   50  |  NAN |
|   41      |   y     | Germany   |   Tool      |     360      | 20   |   80  |  NAN |
|   1       |   x     | India     |   Pen       |      10      | NAN  |  NAN  |  100 |
|   2       |   y     | Australia |   Pencil    |      15      | NAN  |  NAN  |  50  |
|   3       |   x     | Germany   |   Eraser    |       5      | NAN  |  NAN  |  20  |
|   4       |   y     | India     |   Box       |      80      | NAN  |  NAN  |  200 |
|------------------------------------------------------------------------------------|

请注意,在此示例中,所有列中都包含项目ID,源和国家/地区等列,但所有列中可能不会出现其他列。

原始数据中的列数也大约为150.每张表中的行数约为3000,我有大约35K这样的表。因此,我希望将所有这些数据加载到pandas中。

0 个答案:

没有答案
相关问题