正如评论中提到的那样,你犯了一个错误,即正在对一个空列表进行循环。
以下是我如何做到这一点的示例,使用有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
read_csv
替换为read_excel
即可。 - jorisdfs
,所以应该循环遍历文件名,然后在循环中使用dfs.append(df)
,之后再使用pd.concat(dfs, ignore_index=True)
。 - joris