将多个excel文件导入python pandas并将它们连接成一个数据框
- 2025-03-11 08:54:00
- admin 原创
- 54
问题描述:
我想将目录中的几个 excel 文件读入 pandas 并将它们连接成一个大数据框。但我还没能弄清楚。我需要一些有关 for 循环和构建连接数据框的帮助:这是我目前所拥有的:
import sys
import csv
import glob
import pandas as pd
# get data file names
path =r'C:DRODCL_rawdata_filesexcelfiles'
filenames = glob.glob(path + "/*.xlsx")
dfs = []
for df in dfs:
xl_file = pd.ExcelFile(filenames)
df=xl_file.parse('Sheet1')
dfs.concat(df, ignore_index=True)
解决方案 1:
正如评论中提到的,您犯的一个错误是循环遍历一个空列表。
我将以 5 个相同的 Excel 文件一个接一个地附加为例来说明如何操作。
(1)进口:
import os
import pandas as pd
(2)列出文件:
path = os.getcwd()
files = os.listdir(path)
files
输出:
['.DS_Store',
'.ipynb_checkpoints',
'.localized',
'Screen Shot 2013-12-28 at 7.15.45 PM.png',
'test1 2.xls',
'test1 3.xls',
'test1 4.xls',
'test1 5.xls',
'test1.xls',
'Untitled0.ipynb',
'Werewolf Modelling',
'~$Random Numbers.xlsx']
(3)挑选“xls”文件:
files_xls = [f for f in files if f[-3:] == 'xls']
files_xls
输出:
['test1 2.xls', 'test1 3.xls', 'test1 4.xls', 'test1 5.xls', 'test1.xls']
(4)初始化空数据框:
df = pd.DataFrame()
(5)循环遍历文件列表以附加到空数据框:
for f in files_xls:
data = pd.read_excel(f, 'Sheet1')
df = df.append(data)
(6)享受你的新数据框。:-)
df
输出:
Result Sample
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
5 f 6
6 g 7
7 h 8
8 i 9
9 j 10
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
5 f 6
6 g 7
7 h 8
8 i 9
9 j 10
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
5 f 6
6 g 7
7 h 8
8 i 9
9 j 10
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
5 f 6
6 g 7
7 h 8
8 i 9
9 j 10
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
5 f 6
6 g 7
7 h 8
8 i 9
9 j 10
解决方案 2:
有一个更简洁的方法可以做到这一点。
# import libraries
import pandas as pd
from glob import glob
# get the absolute paths of all Excel files
all_excel_files = glob("/path/to/Excel/files/*.xlsx")
# read all Excel files at once
df = pd.concat(pd.read_excel(excel_file) for excel_file in all_excel_files)
解决方案 3:
您可以在里面使用列表推导concat
:
import os
import pandas as pd
path = '/path/to/directory/'
filenames = [file for file in os.listdir(path) if file.endswith('.xlsx')]
df = pd.concat([pd.read_excel(path + file) for file in filenames], ignore_index=True)
其ignore_index = True
索引df
将被标记为0, ..., n - 1。
解决方案 4:
这适用于 Python 2.x
位于 Excel 文件所在的目录中
参见http://pbpython.com/excel-file-combine.html
import numpy as np
import pandas as pd
import glob
all_data = pd.DataFrame()
for f in glob.glob("*.xlsx"):
df = pd.read_excel(f)
all_data = all_data.append(df,ignore_index=True)
# now save the data frame
writer = pd.ExcelWriter('output.xlsx')
all_data.to_excel(writer,'sheet1')
writer.save()
解决方案 5:
可以按照以下方式完成:
import pandas as pd
import glob
all_data = pd.DataFrame()
for f in glob.glob("/path/to/directory/*.xlsx"):
df = pd.read_excel(f)
all_data = all_data.append(df,ignore_index=True)
all_data.to_csv("new_combined_file.csv")
解决方案 6:
#捷径
import pandas as pd
from glob import glob
dfs=[]
for f in glob("data/*.xlsx"):
dfs.append(pd.read_excel(f))
df=pd.concat(dfs, ignore_index=True)
解决方案 7:
import pandas as pd
import os
os.chdir('...')
#read first file for column names
fdf= pd.read_excel("first_file.xlsx", sheet_name="sheet_name")
#create counter to segregate the different file's data
fdf["counter"]=1
nm= list(fdf)
c=2
#read first 1000 files
for i in os.listdir():
print(c)
if c<1001:
if "xlsx" in i:
df= pd.read_excel(i, sheet_name="sheet_name")
df["counter"]=c
if list(df)==nm:
fdf=fdf.append(df)
c+=1
else:
print("headers name not match")
else:
print("not xlsx")
fdf=fdf.reset_index(drop=True)
#relax
解决方案 8:
import pandas as pd
import os
files = [file for file in os.listdir('./Salesfolder')]
all_month_sales= pd.DataFrame()
for file in files
df= pd.read_csv("./Salesfolder/"+file)
all_months_data=pd.concat([all_months_sales,df])
all_months_data.to_csv("all_data.csv",index=False)
您可以从文件夹(我的情况是 Salesfolder)读取所有 .xls 文件,本地路径也是如此。使用迭代,您可以将它们放入空数据框中,然后将数据框连接到此。我还将所有月份的数据导出到另一个 csv 中,并将其合并到一个 csv 文件中
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD