调用 pandas 数据框的列上的 timestamp() 方法,

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月24日 04:47:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定