我试图用"时间";形式为";"小时-小时-分钟-分钟-秒-秒";在我的熊猫框中,从对象到日期时间64,因为我想过滤几个小时。
我尝试了new['Time'] = pd.to_datetime(new['Time'], format='%H:%M:%S').dt.time
,它根本没有效果(它仍然是一个对象(。我也试过new['Time'] = pd.to_datetime(new['Time'],infer_datetime_format=True)
得到错误消息:TypeError: <class 'datetime.time'> is not convertible to datetime
我希望能够对我的数据帧进行数小时的排序。
- 如何将对象转换为小时
- 然后我可以按小时过滤吗(例如早上8点之后的所有内容(,或者我必须输入以分钟和秒为单位的准确值来过滤吗
谢谢
如果您希望df['Time']
是datetime64
类型,只需使用
df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S')
print(df['Time'])
这将导致以下列
0 1900-01-01 00:00:00
1 1900-01-01 00:01:00
2 1900-01-01 00:02:00
3 1900-01-01 00:03:00
4 1900-01-01 00:04:00
...
1435 1900-01-01 23:55:00
1436 1900-01-01 23:56:00
1437 1900-01-01 23:57:00
1438 1900-01-01 23:58:00
1439 1900-01-01 23:59:00
Name: Time, Length: 1440, dtype: datetime64[ns]
如果您只想通过.dt.hour
从时间戳范围pd.to_datetime(...)
中提取小时
如果您想按小时对您的值进行分组,您也可以使用(将df['Time']
转换为日期时间后(:
new_df = df.groupby(pd.Grouper(key='Time', freq='H'))['Value'].agg({pd.Series.to_list})
这将返回按小时分组的所有值。
IIUC,您已经从datetime
模块中获得了time
结构:
假设这个数据帧:
from datetime import time
df = pd.DataFrame({'Time': [time(10, 39, 23), time(8, 47, 59), time(9, 21, 12)]})
print(df)
# Output:
Time
0 10:39:23
1 08:47:59
2 09:21:12
很少操作:
# Check if you have really `time` instance
>>> df['Time'].iloc[0]
datetime.time(10, 39, 23)
# Sort values by time
>>> df.sort_values('Time')
Time
1 08:47:59
2 09:21:12
0 10:39:23
# Extract rows from 08:00 and 09:00
>>> df[df['Time'].between(time(8), time(9))]
Time
1 08:47:59