ITPub博客

首页 > 应用开发 > > python——pandas合并工作簿数据

python——pandas合并工作簿数据

作者:兔子爱喝奶茶 时间:2019-10-14 09:35:05 0 删除 编辑

数据数据数据



如上图现有6个工作簿,每个工作簿中数据格式如下图,现将6张工作簿中的数据一次性合并至一张工作表。

代码如下(注意缩进):

import os

import pandas as pd

path='./合并工作簿/'

file_list=os.listdir(path)

df=pd.DataFrame(columns=['月份','省份','销量','销售额'])

for file in file_list:

if os.path.splitext(file)[1]=='.xlsx':

df1=pd.read_excel(path+file)

df=pd.concat([df,df1])

df.to_excel('./合并工作簿/汇总表.xlsx',index=False)

运行结果如下:

补充说明:

os.listdir(path='.'):列举指定目录中的文件名,返回list。

pd.DataFrame():创建数据表

os.path.splitext(path):分离文件名与扩展名,返回(f_name, f_extension)元组。

pd.read_excel(filepath_or_buffer):导入excel文件数据,返回DataFrame。

pd.concat([df1,df2]):合并两表数据

df.to_excel(excel_writer,index=False):将df写入excel文件,不包含索引。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69918097/viewspace-3139650/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-26

  • 博文量
    1470
  • 访问量
    11252