我正在使用这行将多个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)