英文:
How do you call timestamp() on column of pandas dataframe?
问题
以下是您提供的代码的翻译部分:
time1 = time2 = time3 = datetime.datetime(2022, 12, 2, 8, 15)
rows = pd.DataFrame(
{
"id": [1, 1, 1],
"time": [dt1, dt2, dt3],
})
当我执行以下操作时:
rows.time.dt.timestamp()
我会得到以下错误:
AttributeError: 'DatetimeProperties' object has no attribute 'timestamp'
我可以在每个单独的rows.time.iloc[i]
上调用timestamp()
,但我希望对整个列执行此操作。
英文:
time1 = time2 = time3 = datetime.datetime(2022, 12, 2, 8, 15)
rows = pd.DataFrame(
{
"id": [1, 1, 1],
"time": [dt1, dt2, dt3],
})
When I do
rows.time.dt.timestamp()
I get the error
AttributeError: 'DatetimeProperties' object has no attribute 'timestamp'
I can call timestamp()
on each individual rows.time.iloc[i]
, but I would like to do it on the whole column.
答案1
得分: 3
你误解了DatetimeIndex
和单独的datetime
实例之间的区别。
如果使用dt
访问器,您可以访问DatetimeIndex
实例的某些属性和方法。在这里,timestamp
不是DatetimeIndex
的方法,而是datetime
实例的方法。
如果要以矢量化的方式获取timestamp
,请使用numpy:
>>> rows.time.values.astype(float) / 10**9
array([1.6699689e+09, 1.6699689e+09, 1.6699689e+09])
除以10**9是因为numpy将datetime转换为纳秒,而timestamp以秒为单位返回一个值。
英文:
You miss understand the difference between a DatetimeIndex
and individual datetime
instances.
If you use the dt
accessor, you have access to certain attributes and methods from DatetimeIndex
instance. Here timestamp
is not a method of DatetimeIndex
but a method of datetime
instance.
If you want to get the timestamp
in a vectorized way, use numpy:
>>> rows.time.values.astype(float) / 10**9
array([1.6699689e+09, 1.6699689e+09, 1.6699689e+09])
Divide by 10**9 because numpy convert the datetime as nanoseconds and timestamp returns a value in seconds.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论