2014-01-30 3 views
0

팬더의 열로 기록을 쌓아 : 기본적으로 행을 그룹화변형시키는 나는 이런 식으로 뭔가를 보이는 dataframe이

report action label_a label_b label_c 
0  1 disable  1  1  1 
1  2 alert  0  1  1 
2  3 ignore  1  0  1 

:

import pandas as pd 
df = pd.read_csv('temp.csv', index_col=None) 

print(df) 
>>>> 

    report action label 
0  1 disable label_a 
1  1 disable label_b 
2  1 disable label_c 
3  2 alert label_b 
4  2 alert label_c 
5  3 ignore label_a 
6  3 ignore label_c 

내가 무엇을 하시겠습니까으로 변환입니다 함께 report (및 action, 그러나 action은 항상 모든 report 행에 대해 동일 함), 레이블이 자신의 열에 1 또는 0으로 표시되어 해당 레이블이 존재하는지 여부를 나타냅니다 원래 데이터의 행

This SO question gets me pretty close 그러나 그룹화 된 행에서 라벨 데이터를 잃지 않고 report으로 그룹화하는 방법을 알아낼 수 없습니다.

답변

3

사용 pivot_table() :

df.pivot_table(rows=("report", "action"), 
       cols="label", 
       values="label", 
       aggfunc="count").fillna(0) 

출력 :

label   label_a label_b label_c 
report action        
1  disable  1  1  1 
2  alert   0  1  1 
3  ignore   1  0  1 
관련 문제