在panda中组合CSV文件时尝试catch条件



我正在使用这行将多个csv文件组合到一个数据帧中

df = pd.concat(map(pd.read_csv, files), ignore_index=True)

我之前使用的是for循环,在该循环中我一次组合两个数据帧。这使我能够使用try-catch语句来捕获由空的/格式错误的csv文件引起的任何错误。但是,在顶部显示单行命令的情况下,如何输入类似的try-catch条件?

try:

files = ['file1.csv', 'file2.csv', 'file3.csv']
def readcsv(path):
try:
dff = pd.read_csv(path)
except pd.errors.EmptyDataError:
print('error')
dff = pd.DataFrame([]) #or anything else when error happen
#I put empty dataframe here so the concat don't fail, but you can decide the behaviour you want when error happen (concat will fail if error happens...)
return dff
df = pd.concat(map(readcsv, files), ignore_index=True)

最新更新