Pandas Groupby Agg函数不Redu

2024-06-28 18:57:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个聚合函数,我已经在我的工作中使用了很长一段时间了。其思想是,如果传递给函数的序列长度为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 Lprint 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')

这表示每个组只作为一个系列传递给函数一次。

有谁能帮我理解为什么这是失败的?我在许多数据集中成功地使用了这个函数。。。。

谢谢


Tags: andofthe函数dfreturnisline
2条回答

我真的不能解释你为什么,但是根据我的经验,listpandas.DataFrame中并不能很好地工作。

我通常用tuple代替。 这将起作用:

def MakeList(x):
    T = tuple(x)
    if len(T) > 1:
        return T
    else:
        return T[0]

DF_Agg = DFGrouped.agg({'s.m.v.' : MakeList})

     date line_code           s.m.v.
0  2013-04-02    401101   (7.76, 25.564)
1  2013-04-02    401102           25.564
2  2013-04-02    401103             9.55
3  2013-04-02    401104             4.87
4  2013-04-02    401105   (7.76, 25.564)
5  2013-04-02    401106  (5.282, 25.564)
6  2013-04-02    401107            5.282

这是数据帧中的故障。如果聚合器返回第一个组的列表,它将失败,并出现您提到的错误;如果它返回第一个组的非列表(非系列),它将正常工作。损坏的代码位于groupby.py中:

def _aggregate_series_pure_python(self, obj, func):

    group_index, _, ngroups = self.group_info

    counts = np.zeros(ngroups, dtype=int)
    result = None

    splitter = get_splitter(obj, group_index, ngroups, axis=self.axis)

    for label, group in splitter:
        res = func(group)
        if result is None:
            if (isinstance(res, (Series, Index, np.ndarray)) or
                    isinstance(res, list)):
                raise ValueError('Function does not reduce')
            result = np.empty(ngroups, dtype='O')

        counts[label] = group.shape[0]
        result[label] = res

注意if result is Noneisinstance(res, list。 你的选择是:

  1. 伪造groupby().agg(),因此它看不到第一个组的列表,或者

  2. 自己进行聚合,使用上面那样的代码,但不要进行错误的测试。

相关问题 更多 >