python pandas 时间序列年份提取

python pandas time series year extraction

我有一个包含时间戳的 DF:

0     2005-08-31 16:39:40
1     2005-12-28 16:00:34
2     2005-10-21 17:52:10
3     2014-01-28 12:23:15
4     2014-01-28 12:23:15
5     2011-02-04 18:32:34
6     2011-02-04 18:32:34
7     2011-02-04 18:32:34

我想从每个时间戳中提取年份,在 DF 中创建额外的列,如下所示:

0     2005-08-31 16:39:40 2005
1     2005-12-28 16:00:34 2005
2     2005-10-21 17:52:10 2005
3     2014-01-28 12:23:15 2014
4     2014-01-28 12:23:15 2014
5     2011-02-04 18:32:34 2011
6     2011-02-04 18:32:34 2011
7     2011-02-04 18:32:34 2011

显然我可以遍历所有 DF 条目,去掉日期的前 4 个字符。这是非常慢的。我想知道是否有一种快速的 python 方法可以做到这一点。 我看到可以通过 DF = pd.to_datetime(DF,'%Y-%m-%d %H:%M:%S') 将列转换为日期时间格式但是当我尝试然后应用datetime.datetime.year(DF) 它不起作用。我还需要将时间戳解析为月份和年-月的组合等等...... 请帮忙。 谢谢

不需要为每一行应用一个函数有一个新的 datetime accessor you can call to access the year 属性:

In [35]:

df1['year'] = df1['timestamp'].dt.year
df1
Out[35]:
            timestamp  year
0 2005-08-31 16:39:40  2005
1 2005-12-28 16:00:34  2005
2 2005-10-21 17:52:10  2005
3 2014-01-28 12:23:15  2014
4 2014-01-28 12:23:15  2014
5 2011-02-04 18:32:34  2011
6 2011-02-04 18:32:34  2011
7 2011-02-04 18:32:34  2011

如果您的时间戳是 str 那么您可以使用 pd.to_dateime:

转换为 datetime64
df['timestamp'] = pd.to_datetime(df['timestamp'])

您可以像上面那样使用 dt 访问月份和其他属性。

对于 0.15.0 之前的版本,您可以执行以下操作:

df1['year'] = df1['timestamp'].apply(lambda x: x.year)