【发布时间】:2020-01-08 18:12:18
【问题描述】:
给定一个示例表df如下,如何计算TIME1, TIME2, TIME3.的平均日期
df['AVG_TIME'] = df[['TIME1', 'TIME2', 'TIME3']].mean(axis=1)
这将返回 NaN 值
ID TIME1 TIME2 TIME3
0 2018-07-11 2018-07-09 2018-07-12
1 2018-07-12 2018-06-12 2018-07-15
2 2018-07-13 2018-06-13 2018-08-03
3 2019-09-11 2019-08-11 2019-09-01
4 2019-09-12 2019-08-12 2019-09-15
【问题讨论】:
-
你的专栏是
datetime吗? -
如何将日期时间对象转换为 (int64) 之类的时间戳,然后计算平均值?
-
超级奇怪的情况,
mean是为一系列 datetime64 定义的,但不是 DataFrame。df.apply(pd.Series.mean, axis=1)是一种方法,虽然有一个申请 :(。可能最简单的做法df.astype('int64').mean(1).astype('datetime64[ns]') -
@ALollz 用我的真实数据尝试了你的方法,“TypeError: ('DatetimeIndex cannot perform the operation mean', 'occurred at index 12')”
-
@user3280146 它有效。我使用了astype(np.int64).mean(axis=1),然后通过pd.to_datetime函数将其转换回datetime。