python - 加权平均日期时间,关闭但仅限某些月份

标签 python pandas numpy

我正在计算一系列日期时间的加权平均值(并且一定是做错了,因为我无法解释以下内容):

import pandas as pd
import numpy as np

foo = pd.DataFrame({'date': ['2022-06-01', '2022-06-16'],
                    'value': [1000, 10000]})
foo['date'] = pd.to_datetime(foo['date'])
bar = np.average(foo['date'].view(dtype='float64'), weights=foo['value'])
print(np.array(bar).view(dtype='datetime64[ns]'))

返回 2022-06-14T15:16:21.818181818,这是预期的。

将月份更改为七月:

foo = pd.DataFrame({'date': ['2022-07-01', '2022-07-16'],
                    'value': [1000, 10000]})
foo['date'] = pd.to_datetime(foo['date'])
bar = np.average(foo['date'].view(dtype='float64'), weights=foo['value'])
print(np.array(bar).view(dtype='datetime64[ns]'))

返回2022-07-14T23:59:53.766924660, 当预期结果是 2022-07-14T15:16:21.818181818

预期结果,在 Excel 中计算:

enter image description here

我忽略了什么?

编辑:其他详细信息

  • 我的真实数据集要大得多,如果可能的话我想使用 numpy。
  • foo['date'] 可以假定为没有时间部分的日期,但加权平均值将具有时间部分。

最佳答案

我强烈怀疑这是分辨率/舍入问题。

我假设为了平均日期,这些日期被转换为时间戳 - 然后结果被转换回日期时间对象。但 pandas 的工作时间为纳秒,因此时间戳值分别乘以 1000 和 10000,超过 2**52 - 即超过 64 位 float 的尾数能力。

相反,Excel 的工作时间是毫秒,所以这里没有问题; Python 的 datetime.datetime 以微秒为单位,所以仍然没有问题:

dt01 = datetime(2022,7,1)
dt16 = datetime(2022,7,16)
datetime.fromtimestamp((dt01.timestamp()*1000 + dt16.timestamp()*10000)/11000)
datetime.datetime(2022, 7, 14, 15, 16, 21, 818182)

因此,如果您需要使用 numpy/pandas,我想您最好的选择是将日期从“开始”日期(即定义“自定义纪元”)转换为时间增量,并计算这些值的加权平均值。

关于python - 加权平均日期时间,关闭但仅限某些月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72984658/

相关文章:

python - 我如何获得两个相同的python列表的元素?

python - 有效地 reshape pandas 数据框列中的数组

python - 将对象转换为时间 Pandas 并在时间之间进行过滤

python - MATLAB 引擎和 Imatest IT 的导入冲突

python - pandas 每日平均值,pandas.resample

python - 为包含深度嵌套 numpy 数组的 Python 对象实现 __eq__

python - 在numpy矩阵中查找最大列值的行索引

python - Numpy - 如何将向量索引数组转换为掩码?

Python matplotlib 在 Windows 7 上为 freetype、png 包安装问题

python - 类型错误 : cannot handle this type -> object when using pandas rolling(). 应用(lambda:)