복붙노트

[PYTHON] Pandas Groupby Agg 기능이 저하되지 않음

PYTHON

Pandas Groupby Agg 기능이 저하되지 않음

나는 오랫동안 내 작업에 사용한 집계 함수를 사용하고 있습니다. 함수에 전달 된 시리즈의 길이가 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 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]

이것은 문제없이 실행되며 print 문은 다음과 같습니다.

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에서 함수로 한 번만 전달됨을 나타냅니다.

아무도 왜 이것이 실패하고 있는지 이해할 수 있습니까? 나는 많은 데이터 세트에서이 기능을 성공적으로 사용했다.

감사

해결법

  1. ==============================

    1.왜 그런지 설명 할 수는 없지만 pandas.DataFrame의 경험 목록에서 잘 작동하지는 않습니다.

    왜 그런지 설명 할 수는 없지만 pandas.DataFrame의 경험 목록에서 잘 작동하지는 않습니다.

    나는 보통 대신 튜플을 사용한다. 그게 효과가 있습니다 :

    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
    
  2. ==============================

    2.이것은 DataFrame의 잘못된 기능입니다. 집계자가 첫 번째 그룹에 대한 목록을 반환하면 언급 한 오류로 실패합니다. 첫 번째 그룹에 대해 비 목록 (비 시리즈)을 반환하면 정상적으로 작동합니다. 깨진 코드는 groupby.py에 있습니다 :

    이것은 DataFrame의 잘못된 기능입니다. 집계자가 첫 번째 그룹에 대한 목록을 반환하면 언급 한 오류로 실패합니다. 첫 번째 그룹에 대해 비 목록 (비 시리즈)을 반환하면 정상적으로 작동합니다. 깨진 코드는 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
    

    결과가 None이고 isinstance (res, list. 선택할 수있는 옵션은 다음과 같습니다.

  3. from https://stackoverflow.com/questions/27439023/pandas-groupby-agg-function-does-not-reduce by cc-by-sa and MIT license