AttributeError: 'TimedeltaProperties' 对象没有属性 'minute'

Le *_*off 4 python timedelta attributeerror python-datetime

我有一个看起来像这样的数据框

df

[output]:
date        time
2020-02-28  00:30:45
2020-02-28  00:30:45
2020-03-09  00:21:06
2020-03-09  00:21:06
2020-03-09  00:21:06
Run Code Online (Sandbox Code Playgroud)

df.time.dtype

[output]: dtype('<m8[ns]')
Run Code Online (Sandbox Code Playgroud)

我想使用以下命令提取时间变量中的分钟数

df.time.dt.minute
Run Code Online (Sandbox Code Playgroud)

但相反,我有这个错误

AttributeError: 'TimedeltaProperties' object has no attribute 'minute'
Run Code Online (Sandbox Code Playgroud)

有人知道如何解决这个问题吗?

MrF*_*pes 5

timedelta正如错误告诉您的那样,您的“时间”列是 dtype ;您可以使用该total_seconds()方法转换为秒并除以 60 以获得分钟。

如果您想要功能齐全的日期时间列,请结合使用“日期”和“时间”。然后你可以使用.dt.minute.

前任:

import pandas as pd
df = pd.DataFrame({'time': pd.to_timedelta(['00:30:45','00:30:45','00:21:06','00:21:06','00:21:06']),
                   'date': pd.to_datetime(['2020-02-28','2020-02-28','2020-03-09','2020-03-09','2020-03-09'])})

# to get the "total minutes":
df['minutes'] = df['time'].dt.total_seconds()/60
df['minutes']
# 0    30.75
# 1    30.75
# 2    21.10
# 3    21.10
# 4    21.10
# Name: minutes, dtype: float64
Run Code Online (Sandbox Code Playgroud)

[pd.Timedelta 文档]

# to get a column of dtype datetime:
df['DateTime'] = df['date'] + df['time']

# now you can do:
df['DateTime'].dt.minute
# 0    30
# 1    30
# 2    21
# 3    21
# 4    21
# Name: DateTime, dtype: int64
Run Code Online (Sandbox Code Playgroud)