我想将目录中的几个 Excel 文件读取到 pandas 中,并将它们连接到一个大数据框中。但我还没能弄清楚。我需要一些有关 for 循环和构建串联数据框的帮助: 这是我到目前为止所拥有的:
import sys
import csv
import glob
import pandas as pd
# get data file names
path =r'C:\DRO\DCL_rawdata_files\excelfiles'
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)
正如评论中提到的,您犯的一个错误是循环遍历一个空列表。
以下是我的做法,使用具有 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
这适用于 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()
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。
有一种更简洁的方法可以做到这一点。
# import libraries
import glob
import pandas as pd
# get the absolute path of all Excel files
all_excel_files = glob.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)
这可以通过以下方式完成:
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")
#快捷方式
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)
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
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 文件中