【发布时间】:2015-08-10 21:35:16
【问题描述】:
我试图理解为什么直接在一个组上调用 count() 会返回正确的答案(在本例中,该组中有 2 行),但通过 agg() 函数中的 lambda 调用 count 会返回纪元(“1970-01-01 00:00:00.000000002”)。
# Using groupby(lambda x: True) in the code below just as an illustrative example.
# It will always create a single group.
x = DataFrame({'time': [np.datetime64('2005-02-25'), np.datetime64('2006-03-30')]}).groupby(lambda x: True)
display(x.count())
>>time
>>True 2
display(x.agg(lambda x: x.count()))
>>time
>>True 1970-01-01 00:00:00.000000002
这可能是熊猫的一个错误吗?我在用 熊猫版本:0.16.1 IPython 版本:3.1.0 numpy 版本:1.9.2
无论我使用标准 python 日期时间、np.datetime64 还是熊猫时间戳,我都会得到相同的结果。
编辑(根据@jeff 接受的答案,看起来我可能需要在应用不返回日期时间类型的聚合函数之前强制转换为 dtype 对象):
dt = [datetime.datetime(2012, 5, 1)] * 2
x = DataFrame({'time': dt})
x['time2'] = x['time'].astype(object)
display(x)
y = x.groupby(lambda x: True)
y.agg(lambda x: x.count())
>>time time2
>>True 1970-01-01 00:00:00.000000002 2
【问题讨论】:
标签: python datetime pandas count aggregate