【发布时间】:2020-02-06 22:03:04
【问题描述】:
我正在尝试执行以下操作:
pd.concat([A,B], axis = 1).groupby("status_reason")["closing_time"].mean()
在哪里
- A 是一个名为“status_reason”(分类值)的系列
- B 是一个名为“closure_time”(TimeDelta 值)的系列
例子:
In : A.head(5)
Out:
0 -1 days +11:35:00
1 -10 days +07:13:00
2 NaT
3 NaT
4 NaT
Name: closing_time, dtype: timedelta64[ns]
In : B.head(5)
Out:
0 Won
1 Canceled
2 In Progress
3 In Progress
4 In Progress
Name: status_reason, dtype: object
出现以下错误:
DataError: No numeric types to aggregate
请注意:我试图执行平均,甚至隔离每个类别
现在,我在网上看到了几个和我类似的问题,所以我尝试了这个:
pd.to_timedelta(pd.concat([pd.to_numeric(A),B], axis = 1).groupby("status_reason")["closing_time"].mean())
这只是将 Timedelta 转换为 int64,反之亦然。但是结果很奇怪(数字太高了)
为了排查情况,我写了如下代码:
xxx = pd.concat([A,B], axis = 1)
xxx.closing_time.mean()
#xxx.groupby("status_reason")["closing_time"].mean()
第二行工作正常,没有将 Timedelta 转换为 Int64。第三行不起作用,并再次返回 DataError。
我在这里很困惑!我错过了什么?
我想查看每个“状态原因”的“关闭时间”的平均值!
编辑
如果我尝试这样做:(隔离具有特定状态的行而不分组)
yyy = xxx[xxx["status_reason"] == "In Progress"]
yyy["closing_time"].mean()
结果是:
Timedelta('310 days 21:18:05.454545')
但如果我这样做:(用特定的状态分组隔离行)
yyy = xxx[xxx["status_reason"] == "In Progress"]
yyy.groupby("status_reason")["closing_time"].mean()
结果又是:
DataError: No numeric types to aggregate
最后,如果我这样做:(转换和转换回来)(让我们称之为:特殊示例)
yyy = xxx[xxx["status_reason"] == "In Progress"]
yyy.closing_time = pd.to_numeric (yyy.closing_time)
pd.to_timedelta(yyy.groupby("status_reason")["closing_time"].mean())
我们回到我注意到的第一个问题:
status_reason
In Progress -105558 days +10:08:05.605064
Name: closing_time, dtype: timedelta64[ns]
EDIT2
如果我这样做:(转换为秒并转换回来)
yyy = xxx[xxx["status_reason"] == "In Progress"]
yyy.closing_time = A.dt.seconds
pd.to_timedelta(yyy.groupby("status_reason")["closing_time"].mean(), unit="s" )
结果是
status_reason
In Progress 08:12:38.181818
Name: closing_time, dtype: timedelta64[ns]
如果我删除 NaN,或者我用 0 填充它们,也会发生相同的结果:
yyy = xxx[xxx["status_reason"] == "In Progress"].dropna()
yyy.closing_time = A.dt.seconds
pd.to_timedelta(yyy.groupby("status_reason")["closing_time"].mean(), unit="s" )
但是数字与我们在第一次编辑中看到的非常不同! (特例)
-105558 days +10:08:05.605064
另外,让我用 dropna() 运行相同的代码(特殊示例):
310 days 21:18:05.454545
再一次,让我们用 fillna(0) 运行相同的代码(特殊示例):
3 days 11:14:22.819472
这无济于事。我可能应该准备导出这些数据,并将它们发布到某个地方:Here we go
【问题讨论】:
标签: python pandas type-conversion timedelta