Python代码将工作表名称创建为新列并合并Excel中的所有工作表

问题描述 投票:1回答:1

我是Python新手,如果有一个包可以执行以下操作,该怎么办:

我需要创建一个合并的excel文件,其中工作表名称作为工作表中每一行的新属性

F1.xlsx有A35,A74,B97等,因为工作表名称F2.Xlsx有AX54,BT25等,C是工作表名称

F1.xlsx

表A35有

col1  col2    col3
XYZ       100     Ex-1

B97表有

col1   col2    col3 
ABC    101     Ex-2

F2.xlsx

表AX54有

col1   col2    col3 
XYZefg     110      Ex-3 

B97表有

col1   col2    col3 
ABCef   105    Ex-4

我希望最终文件是:

col5    col4    col1    col2    col3
F1      A35     XYZ     100    Ex-1
F2      B97     ABC     101    Ex-2

enter image description here

enter image description here

python excel python-3.x pandas
1个回答
0
投票

你可以这样做:

import os
from glob import glob

f_mask = r'D:\temp\.data\47894067\*.xlsx'

df = \
pd.concat([df.assign(file=os.path.splitext(os.path.basename(f))[0],
                     sheet=sheet)
           for f in glob(f_mask)
           for sheet, df in pd.read_excel(f, sheet_name=None).items()],
          ignore_index=True)

结果:

In [2]: df
Out[2]:
     col1   col2  col3 file sheet
0     XYZ  100.0  Ex-1   F1   A35
1     ABC  101.0  Ex-2   F1   B97
2  XYZefg  110.0  Ex-3   F2  AX54
3   ABCef  105.0  Ex-4   F2   B97
© www.soinside.com 2019 - 2024. All rights reserved.