【问题标题】:Python Code to create sheet name as a new column and merge all the sheets in ExcelPython代码将工作表名称创建为新列并合并Excel中的所有工作表
【发布时间】:2018-06-02 07:22:30
【问题描述】:

我是Python新手,看看有没有包可以做以下事情:

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

F1.xlsx 具有 A35、A74、B97 等,作为工作表名称 F2.Xlsx 有 AX54,BT25 ETC.,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

【问题讨论】:

  • 这不是一个基本的编程问题......事实上它太宽泛了。你试过什么?
  • xlsxwriter 包可能是您正在寻找的。​​span>

标签: python excel python-3.x pandas


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 感谢您发布解决方案 Max。我收到以下错误。您是否在使用除 pandas、nupy、os 和 glob 之外的任何其他软件包??? -> 3081 return object.__getattribute__(self, name) 3082 3083 def __setattr__(self, name, value): AttributeError: 'Series' object has no attribute 'assign'
  • @user5775949,这很奇怪,循环中的df应该是DataFrame,而不是Series...
  • @user5775949,希望你在调用pd.read_excel()时没有添加squeeze=True参数?
猜你喜欢
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
相关资源
最近更新 更多