2017-10-27 4 views
0

현재 CSV 데이터를 집계하기 위해 팬더에서 groupby 함수를 사용하려고합니다.팬더 응축 그룹화

이 나는 ​​CSV 현재 가지고있는 데이터의 작은 샘플입니다 :

은 현재 로선
Company,School,Number,Type 
Adtelem Global Education Inc.,Carrington,3,For-Profit 
Adtelem Global Education Inc.,Carrington,4,For-Profit 
Adtelem Global Education Inc.,Carrington,1,For-Profit 
Adtelem Global Education Inc.,Carrington,4,For-Profit 
Adtelem Global Education Inc.,Carrington,3,For-Profit 
Adtelem Global Education Inc.,Carrington,3,For-Profit 
Adtelem Global Education Inc.,DeVry Institute of Technology,4,For-Profit 
Adtelem Global Education Inc.,DeVry Institute of Technology,4,For-Profit 
Adtelem Global Education Inc.,DeVry Institute of Learning,16, For-Profit 
Adtelem Global Education Inc.,DeVry Institute of Learning,9,  
Career Education Corporation,Le Cordon Blue College of Culinary Arts,6,For-Profit 
Career Education Corporation,Le Cordon Blue College of Culinary Arts,23,For-Profit 

, 동일한 "학교"컬럼의 반복 (캐링턴, Devry 등의 숫자가 .) 나는 그들을 압축하고 싶다. 더 구체적으로 말하자면, 모든 고유 학교에 대해 1 행을 갖기를 원합니다. 또한 해당 학교의 모든 인스턴스에 대해 Number를 합산하지만 그 학교를 소유 한 회사의 이름 (첫 번째 열)과 학교의 유형 (마지막 기둥).

최종 제품은 다음과 같을 것이다 : 나는이 작업을 수행 할 때 또한 회사를 잃고 각 학교에 부착 된 입력, 그러나

data2 = data.groupby("School").sum() 

:

Company,School,Number,Type 
Adtelem Global Education Inc.,Carrington,18,For-Profit, 
Adtelem Global Education Inc., DeVry Institute of Technology,8,For-Profit 
Adtelem Global Education Inc.,DeVry Institute of Learning,25,For-Profit 
Career Education Corporation,Le Cordon Blue College of Culinary Arts,29,For-Profit 

나는 다음과 같은 코드를 사용했다 . 해결책은 다소 기본적인 것이지만 팬더에 익숙하지 않으므로 모두 도와 드릴 수 있습니다.

+0

질문에 답변이 있으면 [답변을 수락하십시오] (https://stackoverflow.com/help/someone-answers)를 입력하십시오. 감사. –

답변

1

에 의해 그룹에 열 목록을 제공 할 수

df.groupby('School', as_index=False)\ 
    .agg({'Company' : 'first', 'Type' : 'first', 'Number' : 'sum'}) 

            School      Company \ 
0        Carrington Adtelem Global Education Inc. 
1    DeVry Institute of Learning Adtelem Global Education Inc. 
2   DeVry Institute of Technology Adtelem Global Education Inc. 
3 Le Cordon Blue College of Culinary Arts Career Education Corporation 

    Number  Type 
0  18 For-Profit 
1  25 For-Profit 
2  8 For-Profit 
3  29 For-Profit 

나는 그것이 명시 적 집계 모든 열이 더 나은 생각합니다.

0

당신은 내가 groupby + agg 함께 할 것

data2 = data.groupby(["School", "Company", "Type"]).sum()