我正在使用我在工作中已经使用了很长时间的聚合函数。这个想法是,如果传递给函数的系列的长度为 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
and 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')
这表明每个组仅作为系列传递给函数一次。
谁能帮助我理解为什么会失败?我已经在我使用的许多数据集中成功地使用了这个函数......
Thanks