【问题标题】:Python pandas to calculate mean of datetime of multiple columns [duplicate]Python pandas计算多列日期时间的平均值[重复]
【发布时间】: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。

标签: python pandas datetime


【解决方案1】:

这可以按如下方式完成:

import time
import datetime

import pandas as pd

# build the df
c = ['TIME1' ,  'TIME2' ,   'TIME3']
d = [['2018-07-11',  '2018-07-09', '2018-07-12'],
     ['2018-07-12',  '2018-06-12', '2018-07-15'], 
     ['2018-07-13',  '2018-06-13', '2018-08-03'], 
     ['2019-09-11',  '2019-08-11', '2019-09-01'],
     ['2019-09-12',  '2019-08-12', '2019-09-15']]

df = pd.DataFrame(d, columns=c)


# conversion from dates to seconds since epoch (unix time)
def to_unix(s):
    return time.mktime(datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())

# sum the seconds since epoch, calculate average, and convert back to readable date
averages = []
for index, row in df.iterrows():
    unix = [to_unix(i) for i in row]
    average = sum(unix) / len(unix)
    averages.append(datetime.datetime.utcfromtimestamp(average).strftime('%Y-%m-%d'))

df['averages'] = averages

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多