一、情景描述
情景一:
文件夹内有很多excel数据,包含的数据格式一样,我们需要提取每个文件中指定的几列数据汇总到一个文件中(因为是按列索引提取,所以列的顺序可以不一样)
汇总后:
二、python汇总
注意事项:
- 文件所在文件夹内只能有运行文件.py,和需要汇总的文件,不能有其它文件夹,否则会出现运行错误;
- 运行第二遍时需要将第一遍运行得到的结果文件res.xlsx删除,否则也会出现运行错误;
代码如下(示例):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
# -*- coding:utf-8 –*- import os import pandas as pd # 输入参数为excel表格所在目录 def to_one_excel( dir ): dfs = [] # 遍历文件目录,将所有表格表示为pandas中的DataFrame对象 # for root_dir, sub_dir, files in os.walk(r'' + dir): # 第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。 for root_dir, sub_dir, files in os.walk( dir ): # 第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。 for file in files: if file .endswith( 'xlsx' ): # 构造绝对路径 file_name = os.path.join(root_dir, file ) # df = pd.read_excel(file_name) df_1 = list (pd.read_excel(file_name, nrows = 1 )) # 读取excel第一行数据并放进列表 # excel第一行数据返回列表 print (file_name) print ( type (df_1)) print (df_1) # 根据第一行列名获取每个文件中需要列的列索引,返回索引数值 suo_yin_1 = df_1.index( "人员" ) suo_yin_2 = df_1.index( "效率" ) suo_yin_3 = df_1.index( "成绩" ) suo_yin_4 = df_1.index( "产量" ) suo_yin_5 = df_1.index( "节点" ) suo_yin_6 = df_1.index( "备注" ) # 读取文件内容 usecols=[1, 3, 4] 读取第1,3,4列 df = pd.read_excel(file_name, usecols = [suo_yin_1, suo_yin_2, suo_yin_3, suo_yin_4, suo_yin_5, suo_yin_6], sheet_name = 'data' ) # pf = pd.read_excel('xxx.xls', usecols=[1, 3, 4], sheet_name='data') # print(pf) # 追加一列数据,将每个文件的名字追加进该文件的数据中,确定每条数据属于哪个文件 excel_name = file .replace( ".xlsx" , "") # 提取每个excel文件的名称,去掉.xlsx后缀 df[ "文件名" ] = excel_name # 新建列名为“文件名”,列数据为excel文件名 dfs.append(df) # 将新建文件名列追加进汇总excel中 # 行合并 df_concated = pd.concat(dfs) # 构造输出目录的绝对路径 out_path = os.path.join( dir , 'res.xlsx' ) # 输出到excel表格中,并删除pandas默认的index列 df_concated.to_excel(out_path, sheet_name = 'Sheet1' , index = None ) # 调用并执行函数 to_one_excel(r 'E:\py\python3.7\test\test96' ) |
总结
分享:
固守旧我、维持现状的最大好处就是避免改变,这就像陷入一个负能量循环圈,你越害怕去改变,就越不会有动力去改变。
到此这篇关于python按列索引提取文件夹内所有excel指定列汇总的文章就介绍到这了,更多相关python提取excel指定列内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_45365214/article/details/123729128