读取.csv文件时,解析Python中日期的最快方法是什么? [英] The fastest way to parse dates in Python when reading .csv file?
问题描述
我有一个.csv文件,其中有2个单独的列,分别用于日期 c和
时间
。我这样读取文件:
I have a .csv file that has 2 separate columns for 'Date'
and ' Time'
. I read the file like this:
data1 = pd.read_csv('filename.csv', parse_dates=['Date', 'Time'])
但似乎只有'Date'
列采用时间格式,而'Time'
列仍为字符串或采用非时间格式。
But it seems that only the ' Date'
column is in time format while the 'Time'
column is still string or in a format other than time format.
执行以下操作时:
data0 = pd.read_csv('filename.csv')
data0['Date'] = pd.to_datetime(data0['Date'])
data0['Time'] = pd.to_datetime(data0['Time'])
它提供了我想要的数据帧,但需要花费一些时间。
那么,读取文件并从字符串格式转换日期和时间的最快方法是什么?
It gives a dataframe I want, but takes quite some time. So what's the fastest way to read in the file and convert the date and time from a string format?
.csv文件是这样的:
The .csv file is like this:
Date Time Open High Low Close
0 2004-04-12 8:31 AM 1139.870 1140.860 1139.870 1140.860
1 2005-04-12 10:31 AM 1141.219 1141.960 1141.219 1141.960
2 2006-04-12 12:33 PM 1142.069 1142.290 1142.069 1142.120
3 2007-04-12 3:24 PM 1142.240 1143.140 1142.240 1143.140
4 2008-04-12 5:32 PM 1143.350 1143.589 1143.350 1143.589
谢谢!
推荐答案
在这里,您的情况 Time 在 AM / PM >格式,这需要更多时间来解析。
Here, In your case 'Time' is in AM/PM format which take more time to parse.
您可以添加 format 来提高to_datetime()方法的速度。
You can add format to increase speed of to_datetime() method.
data0=pd.read_csv('filename.csv')
# %Y - year including the century
# %m - month (01 to 12)
# %d - day of the month (01 to 31)
data0['Date']=pd.to_datetime(data0['Date'], format="%Y/%m/%d")
# %I - hour, using a -hour clock (01 to 12)
# %M - minute
# %p - either am or pm according to the given time value
# data0['Time']=pd.to_datetime(data0['Time'], format="%I:%M %p") -> around 1 sec
data0['Time']=pd.datetools.to_time(data0['Time'], format="%I:%M %p")
有关更多方法的信息,请参见:熊猫工具
For more methods info : Pandas Tools
有关更多格式选项,请检查- datetime格式指令。
For more format options check - datetime format directives.
对于50万行,它得到了改进速度从60秒左右->在我的系统中为0.01秒。
For 500K rows it improved speed from around 60 seconds -> 0.01 seconds in my system.
您还可以使用:
# Combine date & time directly from string format
pd.Timestamp(data0['Date'][0] + " " + data0['Time'][0])
这篇关于读取.csv文件时,解析Python中日期的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!