【问题标题】:median of panda datetime64 columnpanda datetime64 列的中位数
【发布时间】:2017-10-08 22:23:44
【问题描述】:

有没有办法以日期时间格式计算并返回日期时间列的中位数? 我想计算 python 中 datetime64[ns] 格式的列的中位数。以下是该列的示例:

df['date'].head()

0   2017-05-08 13:25:13.342
1   2017-05-08 16:37:45.545
2   2017-01-12 11:08:04.021
3   2016-12-01 09:06:29.912
4   2016-06-08 03:16:40.422

名称:新近度,数据类型:datetime64[ns]

我的目标是使中位数的日期时间格式与上面的日期列相同:

尝试转换为 np.array:

median_ = np.median(np.array(df['date']))

但这会引发错误:

TypeError: ufunc add cannot use operands with types dtype('<M8[ns]') and dtype('<M8[ns]')

转换为 int64 然后计算中位数并尝试将格式返回为 datetime 不起作用

df['date'].astype('int64').median().astype('datetime64[ns]')

【问题讨论】:

    标签: python python-datetime datetime64


    【解决方案1】:

    你也可以试试quantile(0.5):

    df['date'].astype('datetime64[ns]').quantile(0.5, interpolation="midpoint")
    

    【讨论】:

      【解决方案2】:

      只取中间值怎么样?

      dates = list(df.sort('date')['date'])
      print dates[len(dates)//2]
      

      如果表格已排序,您甚至可以跳过一行。

      【讨论】:

      • 谢谢@kabanus。这很好用。我没有想到要对列的长度进行排序和使用。
      • @T-Jay 乐于助人。不要忘记接受让我感觉良好并为他人谋福利。
      【解决方案3】:

      你很接近,median() 返回一个float,所以首先将其转换为int

      import math
      
      median = math.floor(df['date'].astype('int64').median())
      

      然后将int代表日期转换成datetime64

      result = np.datetime64(median, "ns") #unit: nanosecond
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-29
        • 1970-01-01
        • 2015-08-21
        • 1970-01-01
        • 2018-03-06
        • 1970-01-01
        • 2020-04-28
        相关资源
        最近更新 更多