【发布时间】:2017-04-14 09:26:15
【问题描述】:
我有一个包含一些(数亿)行的数据框。我想有效地将日期时间转换为时间戳。我该怎么做?
我的样本df:
df = pd.DataFrame(index=pd.DatetimeIndex(start=dt.datetime(2016,1,1,0,0,1),
end=dt.datetime(2016,1,2,0,0,1), freq='H'))\
.reset_index().rename(columns={'index':'datetime'})
df.head()
datetime
0 2016-01-01 00:00:01
1 2016-01-01 01:00:01
2 2016-01-01 02:00:01
3 2016-01-01 03:00:01
4 2016-01-01 04:00:01
现在我使用 .apply() 将日期时间逐个值转换为时间戳值,但如果我有一些(数亿)行,则需要很长时间(几个小时):
df['ts'] = df[['datetime']].apply(lambda x: x[0].timestamp(), axis=1).astype(int)
df.head()
datetime ts
0 2016-01-01 00:00:01 1451602801
1 2016-01-01 01:00:01 1451606401
2 2016-01-01 02:00:01 1451610001
3 2016-01-01 03:00:01 1451613601
4 2016-01-01 04:00:01 1451617201
上面的结果就是我想要的。
如果我尝试使用pandas.Series 的.dt 访问器,则会收到错误消息:
df['ts'] = df['datetime'].dt.timestamp
AttributeError: 'DatetimeProperties' 对象没有属性 '时间戳'
如果我尝试创建例如。使用 .dt 访问器的日期时间的日期部分比使用 .apply() 快得多:
df['date'] = df['datetime'].dt.date
df.head()
datetime ts date
0 2016-01-01 00:00:01 1451602801 2016-01-01
1 2016-01-01 01:00:01 1451606401 2016-01-01
2 2016-01-01 02:00:01 1451610001 2016-01-01
3 2016-01-01 03:00:01 1451613601 2016-01-01
4 2016-01-01 04:00:01 1451617201 2016-01-01
我想要类似时间戳的东西...
但我不太了解官方文档:它谈论“Converting to Timestamps”但我没有看到任何时间戳;它只是谈论使用pd.to_datetime() 转换为日期时间而不是时间戳...
pandas.Timestamp 构造函数也不起作用(返回以下错误):
df['ts2'] = pd.Timestamp(df['datetime'])
TypeError:无法将输入转换为时间戳
pandas.Series.to_timestamp 也做出了我想要的完全不同的东西:
df['ts3'] = df['datetime'].to_timestamp
df.head()
datetime ts ts3
0 2016-01-01 00:00:01 1451602801 <bound method Series.to_timestamp of 0 2016...
1 2016-01-01 01:00:01 1451606401 <bound method Series.to_timestamp of 0 2016...
2 2016-01-01 02:00:01 1451610001 <bound method Series.to_timestamp of 0 2016...
3 2016-01-01 03:00:01 1451613601 <bound method Series.to_timestamp of 0 2016...
4 2016-01-01 04:00:01 1451617201 <bound method Series.to_timestamp of 0 2016...
谢谢!!
【问题讨论】:
标签: python datetime pandas timestamp