我想将目标目录中的多个 CSV 文件(数百个文件,每个文件数百行,但列数相同)读取到单个 Python Pandas DataFrame 中。
我写的下面的代码可以运行,但是太慢了。运行 30 个文件需要几分钟(如果我加载所有文件,我应该等待多长时间)。我可以改变什么来让它工作得更快?
此外,在replace函数中,我想将一个“_”(不知道编码,但不是普通编码)替换为“-”(普通utf-8),我该怎么办?我使用 coding=latin-1,因为文件中有法语口音。
#coding=latin-1
import pandas as pd
import glob
pd.set_option('expand_frame_repr', False)
path = r'D:\Python27\mypfe\data_test'
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []
for file_ in allFiles:
df = pd.read_csv(file_, index_col = None, header = 0, sep = ';', dayfirst = True,
parse_dates=['HeurePrevue','HeureDebutTrajet','HeureArriveeSurSite','HeureEffective'])
df.drop(labels=['aPaye','MethodePaiement','ArgentPercu'],axis=1,inplace=True)
df['Sens'].replace("\n", "-", inplace=True,regex=True)
list_.append(df)
print "fichier lu:",file_
frame = pd.concat(list_)
print frame
请您参考如下方法:
您可以尝试以下方法 - 只读取那些真正需要的列,使用列表理解并调用 pd.concat([ ... ], ignore_index=True) 一次,因为它非常慢:
# there is no sense to read columns that you don't need
# specify the column list (EXCLUDING: 'aPaye','MethodePaiement','ArgentPercu')
cols = ['col1', 'col2', 'etc.']
date_cols = ['HeurePrevue','HeureDebutTrajet','HeureArriveeSurSite','HeureEffective']
df = pd.concat(
[pd.read_csv(f, sep = ';', dayfirst = True, usecols=cols,
parse_dates=date_cols)
for f in allFiles
],
ignore_index=True
)
如果您有足够的内存来存储两个 生成的 DF,这应该可以工作...
