我有一个大型的CSV文件,我需要操作与Pandas。阅读documentation,我发现选择engine='c'
有助于加快这一过程。该文档指出要使用此功能,您必须声明数据类型。所以这是我的第一次尝试:
data_types = {
'AccountNumber': object,
'AccountName': object,
'StatsDate': datetime,
'InvoiceDate': datetime,
'Product': object,
'LineItem': object,
'Charges': np.float64
}
df = pd.read_csv('accounting_worksheet.csv',
engine='c',
dtype=data_types,
encoding='utf-8')
但是,Pandas无法识别声明为datetime的项目:
In [10]: df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3669868 entries, 0 to 3669867
Data columns (total 9 columns):
AccountNumber object
AccountName object
StatsDate object
InvoiceDate object
Product object
LineItem object
Charges float64
dtypes: float64(1), object(6)
所以在StackOverflow上挖掘我发现two posts看起来很有帮助并尝试了这一点:
import datetime
def parse_dates(x):
return datetime.strptime(x,'%m/%d/%Y')
data_types = {
'AccountNumber': object,
'AccountName': object,
'StatsDate': datetime,
'InvoiceDate': datetime,
'Product': object,
'LineItem': object,
'Charges': np.float64
}
df = pd.read_csv('accounting_worksheet.csv',
engine='c',
dtype=data_types,
parse_dates=['StatsDate','InvoiceDate'],
date_parser=parse_dates,
encoding='utf-8')
这一次,我得到了正确的dtypes,但导入文件需要几分钟时间:
In [14]: df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3669868 entries, 0 to 3669867
Data columns (total 9 columns):
AccountNumber object
AccountName object
StatsDate datetime64[ns]
InvoiceDate datetime64[ns]
Product object
LineItem object
Charges float64
dtypes: datetime64[ns](2), float64(1), object(4)
目前,我已采用此处概述的第一种方法,然后在导入运行后:
df['StatsDate'] = pd.to_datetime(df['StatsDate'],format='%m/%d/%Y')
df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'],format='%m/%d/%Y')
此文件的大小将继续增长,因此我正在寻找最优化的方法。有更有效的解决方案吗?