我正在使用一个聚合函数,我已经在我的工作中使用了很长一段时间了。其思想是,如果传递给函数的序列长度为1(即组只有一个观测值),则返回该观测值。如果传递的序列长度大于1,则将在列表中返回观测值。
这在有些人看来可能很奇怪,但这不是一个X,Y问题,我有充分的理由想这样做,这与这个问题无关。
这是我一直在使用的函数:
def MakeList(x):
""" This function is used to aggregate data that needs to be kept distinc within multi day
observations for later use and transformation. It makes a list of the data and if the list is of length 1
then there is only one line/day observation in that group so the single element of the list is returned.
If the list is longer than one then there are multiple line/day observations and the list itself is
returned."""
L = x.tolist()
if len(L) > 1:
return L
else:
return L[0]
现在由于某种原因,对于我正在处理的当前数据集,我得到一个ValueError,指出函数没有减少。以下是一些测试数据和我正在使用的其余步骤:
import pandas as pd
DF = pd.DataFrame({'date': ['2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02',
'2013-04-02'],
'line_code': ['401101',
'401101',
'401102',
'401103',
'401104',
'401105',
'401105',
'401106',
'401106',
'401107'],
's.m.v.': [ 7.760,
25.564,
25.564,
9.550,
4.870,
7.760,
25.564,
5.282,
25.564,
5.282]})
DFGrouped = DF.groupby(['date', 'line_code'], as_index = False)
DF_Agg = DFGrouped.agg({'s.m.v.' : MakeList})
在尝试调试时,我将print语句设置为print L
和print x.index
的效果,然后
结果如下:
[7.7599999999999998, 25.564]
Int64Index([0, 1], dtype='int64')
[7.7599999999999998, 25.564]
Int64Index([0, 1], dtype='int64')
出于某种原因,似乎agg
正在将序列两次传递给函数。据我所知,这完全不正常,大概是我的功能没有减少的原因。
例如,如果我编写这样的函数:
def test_func(x):
print x.index
return x.iloc[0]
运行时没有问题,打印语句如下:
DF_Agg = DFGrouped.agg({'s.m.v.' : test_func})
Int64Index([0, 1], dtype='int64')
Int64Index([2], dtype='int64')
Int64Index([3], dtype='int64')
Int64Index([4], dtype='int64')
Int64Index([5, 6], dtype='int64')
Int64Index([7, 8], dtype='int64')
Int64Index([9], dtype='int64')
这表示每个组只作为一个系列传递给函数一次。
有谁能帮我理解为什么这是失败的?我在许多数据集中成功地使用了这个函数。。。。
谢谢
我真的不能解释你为什么,但是根据我的经验,
list
在pandas.DataFrame
中并不能很好地工作。我通常用
tuple
代替。 这将起作用:这是数据帧中的故障。如果聚合器返回第一个组的列表,它将失败,并出现您提到的错误;如果它返回第一个组的非列表(非系列),它将正常工作。损坏的代码位于groupby.py中:
注意
if result is None
和isinstance(res, list
。 你的选择是:伪造groupby().agg(),因此它看不到第一个组的列表,或者
自己进行聚合,使用上面那样的代码,但不要进行错误的测试。
相关问题 更多 >
编程相关推荐