[英]Why am I getting IndexError: list index out of range for this function?
I am trying to concatenate a list of xlsx files.我正在尝试连接 xlsx 文件列表。 Here is my code:
这是我的代码:
import pandas as pd
from glob import glob
files = glob('DS*.xlsx')
files_combined = pd.concat((pd.read_excel(x).assign(filename = x) for x in files))
I get我得到
IndexError: list index out of range
I did a lot of research and it seems that the problem people suspect is that glob returns a blank list.我做了很多研究,似乎人们怀疑的问题是 glob 返回一个空白列表。 However, when I change my code to
但是,当我将代码更改为
import pandas as pd
from glob import glob
files = glob('RC*.xlsx')
print(files)
I get a list of the files I am looking to concatenate.我得到了我想要连接的文件的列表。 I have tried changing my code to
我曾尝试将我的代码更改为
import pandas as pd
from glob import glob
import os
DIR = 'Y:\\files\'
files = glob(os.path.join(DIR, 'DS*.xlsx'))
files_combined = pd.concat((pd.read_excel(x).assign(filename = x)
for x in files))
but I get the same error.但我得到了同样的错误。
I ran this (basically your original code) successfully:我成功地运行了这个(基本上是你的原始代码):
import os
import pandas as pd
from glob import glob
os.chdir('C:/users/xxxx/')
files = glob('*.xlsx')
files_combined = pd.concat((pd.read_excel(x).assign(filename = x) for x in files))
No errors, so I added this and reran:没有错误,所以我添加了这个并重新运行:
print(files_combined)
The result is the concatenation of the 5 xlsx files in my directory.结果是我的目录中的 5 个 xlsx 文件的串联。
Then I wanted to test the "no files" option, so I changed my glob statement:然后我想测试“无文件”选项,所以我改变了我的 glob 语句:
import os
import pandas as pd
from glob import glob
os.chdir('C:/users/xxxx/')
files = glob('*.xlsx1234')
files_combined = pd.concat((pd.read_excel(x).assign(filename = x) for x in files))
Now I get the error "No objects to concatenate".现在我收到错误“没有要连接的对象”。 So a blank list will not return the "list index out of range" error either.
因此,空白列表也不会返回“列表索引超出范围”错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.