我一直在使用一种聚合函数,这个函数已经在我的工作中使用了很长时间。其思想是,如果传递给函数的Series长度为1(即该组只有一个观测值),则返回该观测值。如果传递的Series长度大于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 L
和 print x.index
,输出结果如下:
在尝试调试该问题时,我添加了以下打印语句:print L
和 print x.index
,输出如下:
[7.7599999999999998, 25.564]
Int64Index([0, 1], dtype='int64')
[7.7599999999999998, 25.564]
Int64Index([0, 1], dtype='int64')
因为某种原因,看起来 agg
将 Series 两次传递给函数。据我所知,这完全不正常,很可能是我的函数不能缩小的原因。
例如,如果我写了这样一个函数:
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')
这表明每个组只被作为 Series 一次传递给函数。
有人能帮我理解为什么会失败吗?我在许多数据集中成功使用了这个函数...
谢谢
test_func
函数之所以可以减少计算量是因为它只返回了单个值。你有一个聚合函数返回列表的可用示例吗?它曾经对你有效过吗? - BrenBarntuple(L)
而不是L
。 - Woody Pride