哪个是从给定日期提取日,月和年的最快方法?

问题描述 投票:15回答:2

我将包含150,000行的csv文件读入了熊猫数据框。该数据框具有“日期”字段,日期格式为[[yyyy-mm-dd。我想从中提取月,日和年,然后分别复制到数据框的列中,分别为“月”,“日”和“年”。对于几百条记录,以下两种方法都行得通,但是对于15万条记录,两种方法都需要花费很长的时间才能执行。是否有更快的方式来处理100,000多个记录?

第一种方法:

df = pandas.read_csv(filename) for i in xrange(len(df)): df.loc[i,'Day'] = int(df.loc[i,'Date'].split('-')[2])

第二种方法:

df = pandas.read_csv(filename) for i in xrange(len(df)): df.loc[i,'Day'] = datetime.strptime(df.loc[i,'Date'], '%Y-%m-%d').day

谢谢。
python pandas date datetime accessor
2个回答
32
投票
在0.15.0中,您将可以使用新的.dt访问器在语法上做到这一点。

In [36]: df = DataFrame(date_range('20000101',periods=150000,freq='H'),columns=['Date']) In [37]: df.head(5) Out[37]: Date 0 2000-01-01 00:00:00 1 2000-01-01 01:00:00 2 2000-01-01 02:00:00 3 2000-01-01 03:00:00 4 2000-01-01 04:00:00 [5 rows x 1 columns] In [38]: %timeit f(df) 10 loops, best of 3: 22 ms per loop In [39]: def f(df): df = df.copy() df['Year'] = DatetimeIndex(df['Date']).year df['Month'] = DatetimeIndex(df['Date']).month df['Day'] = DatetimeIndex(df['Date']).day return df ....: In [40]: f(df).head() Out[40]: Date Year Month Day 0 2000-01-01 00:00:00 2000 1 1 1 2000-01-01 01:00:00 2000 1 1 2 2000-01-01 02:00:00 2000 1 1 3 2000-01-01 03:00:00 2000 1 1 4 2000-01-01 04:00:00 2000 1 1 [5 rows x 4 columns]

从0.15.0开始(于2014年9月发布),现在可以使用新的.dt访问器进行以下操作:

df['Year'] = df['Date'].dt.year df['Month'] = df['Date'].dt.month df['Day'] = df['Date'].dt.day


0
投票
我使用下面的代码对我来说非常有效

df['Year']=[d.split('-')[0] for d in df.Date] df['Month']=[d.split('-')[1] for d in df.Date] df['Day']=[d.split('-')[2] for d in df.Date] df.head(5)

© www.soinside.com 2019 - 2024. All rights reserved.