2013-12-19 1 views
6

groupby 함수 응용 프로그램을 디버그하려고 할 때 더미 함수를 사용하여 각 그룹의 함수로 "전달되는 내용을 확인하십시오"라는 것을 someone suggested 디버깅하려고합니다. 그룹에서 변환 또는 적용하기 위해 전달되는 판다 데이터 형식

single column transform 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 


single column (nested) transform 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 


multiple column transform 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 




single column apply 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 


single column (nested) apply 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 


multiple column apply 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 

은 그래서 것 같다

:

    • 단일 열 변환

      import numpy as np 
      import pandas as pd 
      
      np.random.seed(0) # so we can all play along at home 
      
      categories = list('abc') 
      categories = categories * 4 
      data_1 = np.random.randn(len(categories)) 
      data_2 = np.random.randn(len(categories)) 
      
      df = pd.DataFrame({'category': categories, 'data_1': data_1, 'data_2': data_2}) 
      
      def f(x): 
          print type(x) 
          return x 
      
      print 'single column transform' 
      df.groupby(['category'])['data_1'].transform(f) 
      print '\n' 
      
      print 'single column (nested) transform' 
      df.groupby(['category'])[['data_1']].transform(f) 
      print '\n' 
      
      print 'multiple column transform' 
      df.groupby(['category'])[['data_1', 'data_2']].transform(f) 
      
      print '\n' 
      print '\n' 
      
      print 'single column apply' 
      df.groupby(['category'])['data_1'].apply(f) 
      print '\n' 
      
      print 'single column (nested) apply' 
      df.groupby(['category'])[['data_1']].apply(f) 
      print '\n' 
      
      print 'multiple column apply' 
      df.groupby(['category'])[['data_1', 'data_2']].apply(f) 
      

      이 내 표준 출력에 다음을 넣습니다 : 물론, 나는 게임을 해요 : 3 Series

    • 단일 열 (중첩) : 2 Series 3 DataFrame
    • 여러 열 : 3 Series 3 DataFrame
    • 단일 열 적용 : (중첩) 3 Series
    • 단일 열 : 4 DataFrame
    • 복수 열 : 4 DataFrame

여기 무슨 일 이니? 누구든지이 6 개의 호출이 각각 위에서 언급 한 일련의 객체가 지정된 함수로 전달되는 이유를 설명 할 수 있습니까?

+1

2 질문을 확장하십시오 (완전히 대답 할 때 멋진 문서가 될 것입니다). groupy에 2 명의 그룹 작성자가있는 경우가 필요합니다 (입력 항목이 다르지만 그룹화 된 개체의 색인이 포함되어 있음) – Jeff

+0

팬더를 배우려고 시도하면서이 유형의 질문이 많이있었습니다. 지난 한 달 동안. 이런 종류의 일에 좋은 자원이 있습니까? 나는. 하드 코어 소스 코드 다이빙/다시 쓰기와 달리 직관적 인 수준에서 팬더가 어떻게 작동하는지에 대한 일반적인 설명은 무엇입니까? 후드 아래의 – 8one6

+0

은 일반적으로 코드를 작성하고 예제를 작성해야합니다. 일부는 간단하지만 groupby/indexing과 마찬가지로 많은 경우와 데이터 유형을 처리하므로 쉽지 않습니다. 자원은 워드 프로세서/요리 책, Wes의 책 및 SO 질문입니다. – Jeff

답변

4

GroupBy.transform은 사용자의 기능에 대해 fast_path 및 slow_path를 시도합니다.

  • fast_path보기 : DataFrame 객체
  • slow_path으로 함수를 호출 : fast_path의 결과가 slow_path 같은 경우 DataFrame.apply 기능

으로 함수를 호출, 그것은 fast_path를 선택합니다.

https://github.com/pydata/pandas/blob/master/pandas/core/groupby.py#L2277

편집

호출 스택을 검사 할 : 여기

multiple column transform 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.series.Series'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 
<class 'pandas.core.frame.DataFrame'> 

코드 링크이다

다음 출력은 결국 fast_path 선택된 것을 의미한다 :

import numpy as np 
import pandas as pd 

np.random.seed(0) # so we can all play along at home 

categories = list('abc') 
categories = categories * 4 
data_1 = np.random.randn(len(categories)) 
data_2 = np.random.randn(len(categories)) 

df = pd.DataFrame({'category': categories, 'data_1': data_1, 'data_2': data_2}) 

import traceback 
import inspect 
import itertools 

def f(x): 
    flag = True 
    stack = itertools.dropwhile(lambda x:"#stop here" not in x, 
           traceback.format_stack(inspect.currentframe().f_back)) 
    print "*"*20 
    print x 
    print type(x) 
    print 
    print "\n".join(stack) 
    return x 

df.groupby(['category'])[['data_1', 'data_2']].transform(f) #stop here 
+0

저는 각 예제에 대해 "유형"이 3 라인 이상인 이유에 대해 다소 혼란 스럽습니다. 내 데이터 세트에는 정확히 3 개의 그룹이 있습니다. 각 예에는 ** 무언가 **가 정확히 3 개 포함될 것으로 기대됩니다. 팬더가 마침내 뽑아서 처리 할 기능을 묻는다. 그러나 위의 출력과 호환되지 않는 것 같습니다. 마지막 2 건은 각각 4 DataFrames에서 작동하며 그 밖의 것은 없습니다. 거기에 무슨 일이 일어나는지 설명해 주시겠습니까? – 8one6

+0

@ DJ_8one6, 당신은 호출 스택을 인쇄하고 무슨 일이 일어나고 있는지 분석 할 수 있습니다. – HYRY

+0

다중 열 데이터 프레임 (열의 개별 시리즈가 아닌)을 함수로 전달하도록 강제 변환하는 방법이 있습니까? 기본적으로'apply (my_func, axis = 1) '와 같은 동작을 원하지만 동일한 인덱스 (결과적으로 변환이 수행되어야하는 결과)를 반환하도록 강요하지만 열 단위로 작업하는 것이 아니라 원하는대로 결과를 반환 할 수 있습니다. 같은 시간에 여러 열에 액세스). –