【问题标题】:Getting the average from a dataframe consisting of pandas timestamp从包含熊猫时间戳的数据框中获取平均值
【发布时间】:2018-10-31 10:45:30
【问题描述】:

我有两个熊猫系列,closedDatecreatedDate,这些元素是熊猫时间戳,class 'pandas._libs.tslib.Timestampclass 'pandas._libs.tslib.Timestamp

我已经减去了这两个熊猫系列来制作一个列表,age,pandas timedelta。

closedDate = data.iloc[:,1]
createdDate = data.iloc[:,2]
age = [x-y for x,y in zip(closedDate, createdDate)]

现在,我想获得 age 的平均值,但我的代码行出现错误。

在:average_age = functools.reduce(lambda x, y: x + y, age) / len(age)

输出:OverflowError: int too big to convert

我该如何解决这个问题??

谢谢!

【问题讨论】:

    标签: python pandas datetime timedelta


    【解决方案1】:

    您可以并且应该针对此任务使用矢量化函数。

    在此示例中,您可以从另一个中减去一个 pd.Series。然后您可以使用mean 方法计算平均值。

    data = pd.DataFrame({'createdDate': [pd.Timestamp('2018-01-01'),
                                         pd.Timestamp('2018-05-01')],
                         'closedDate': [pd.Timestamp('2018-02-01'),
                                        pd.Timestamp('2018-07-01')]})
    
    closedDate = data['closedDate']
    createdDate = data['createdDate']
    
    ages = closedDate - createdDate
    
    print(ages)
    
    # 0   31 days
    # 1   61 days
    # dtype: timedelta64[ns]
    
    res = ages.mean()
    
    print(res)
    
    # 46 days 00:00:00
    

    在这种情况下使用矢量化函数更好有两个主要原因:

    1. 基础 pd.Timestamp 是数字数组 (source)。
    2. 数组上的zip 表现不如列表上的zip (source)。

    【讨论】:

      【解决方案2】:

      您应该使用 jpp 建议的系列来执行此操作,但除此之外,您可以使用您提供的列表来执行此操作。

      average_age = sum(age, timedelta()) / len(age)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-16
        • 2021-09-25
        • 2018-05-15
        • 2018-10-26
        • 2018-03-14
        • 1970-01-01
        • 1970-01-01
        • 2021-08-20
        相关资源
        最近更新 更多