簡體   English   中英

Datetime dtype是Object而不是Datetime

[英]Datetime dtype is Object not Datetime

我正在嘗試通過時間戳分組。 首先,我必須將獲得的時間(字符串)轉換為日期時間。 轉換日期時間后,我注意到盡管給出了熊貓添加日期的特定格式,但我不需要日期。 我正在努力刪除此內容,僅保留時間對象,但沒有成功。 我為刪除日期所做的任何操作都會將dtype返回給無法執行groupby的對象。

示例數據:

https://miratrix.co.uk/          00:01:55
https://miratrix.co.uk/          00:02:02
https://miratrix.co.uk/          00:02:45
https://miratrix.co.uk/          00:01:22
https://miratrix.co.uk/          00:02:02
https://miratrix.co.uk/app-marketing-agency/          00:02:23
https://miratrix.co.uk/get-in-touch/          00:02:26
https://miratrix.co.uk/get-in-touch/          00:00:18
https://miratrix.co.uk/get-in-touch/          00:02:37
https://miratrix.co.uk/          00:00:31
https://miratrix.co.uk/          00:02:00
https://miratrix.co.uk/app-store-optimization-...          00:02:25
https://miratrix.co.uk/          00:03:36
https://miratrix.co.uk/app-marketing-agency/          00:02:09
https://miratrix.co.uk/get-in-touch/          00:02:14
https://?page_id=16198/          00:00:15
https://videos/channel/UCAQfRNzXGD4BQICkO1KQZUA/          00:09:07
https://miratrix.co.uk/get-in-touch/          00:01:39
https://miratrix.co.uk/app-marketing-agency/          00:01:07

到目前為止我嘗試過的

*Returned Object*
ga_organic['NEW Avg. Time on Page'] = pd.to_datetime(ga_organic['Avg. Time on Page'], format="%H:%M:%S").dt.time

*Returned Datetime but when trying to sample only time it returned an object*
ga_organic['NEW Avg. Time on Page'] = ga_organic['Avg. Time on Page'].astype('datetime64[ns]')

ga_organic['NEW Avg. Time on Page'].dt.time

我有一種關於日期時間的感覺,我不知道,這就是為什么我遇到這個問題。 歡迎任何幫助或指示。

####更新####

感謝ALollz為時間戳提供了解決方案。

ga_organic['NEW Avg. Time on Page'] = pd.to_timedelta(ga_organic['Avg. Time on Page'])

但是,使用GroupBy通過以下方法時,我仍然會遇到相同的錯誤:

avg_time = ga_organic.groupby(ga_organic.index)['NEW Avg. Time on Page'].mean()

錯誤:“ DataError:沒有要聚合的數字類型”

是否有處理日期時間分組的特定功能?

似乎groupby無法將timedelta64識別為數字類型。 有幾種解決方法,或者使用numeric_only=False或使用total_seconds

import pandas as pd

#df = pd.read_clipboard(header=None)
#df[1] = pd.to_timedelta(df[1])

df.groupby(df.index//2)[1].mean()
#DataError: No numeric types to aggregate

# To fix pass `numeric_only=False`
df.groupby(df.index//2)[1].mean(numeric_only=False)
#0   00:01:58.500000
#1   00:02:03.500000
#2   00:02:12.500000
#3          00:01:22
#4          00:01:34
#5   00:02:12.500000
#6   00:02:52.500000
#7   00:01:14.500000
#8          00:05:23
#9          00:01:07
#Name: 1, dtype: timedelta64[ns]

使用簡單的float值和.total_seconds

df[1] = df[1].dt.total_seconds()

df.groupby(df.index//2)[1].mean()
#0    118.5
#1    123.5
#2    132.5
#3     82.0
#4     94.0
#5    132.5
#6    172.5
#7     74.5
#8    323.0
#9     67.0
#Name: 1, dtype: float64

可以使用指定unit='s' pd.to_timedelta將其轉換回去

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM