2016-06-07 2 views
1

파이썬에서 데이터 프레임이 있습니다. 그것에는 여러 사람들이있는 한 개의 열과 그들이 구입 한 다른 제품이 들어있는 한 개의 열이 있습니다. 각 제품에 대해 구매 한 금액을 각 사람별로 요약하려고합니다. 그러므로 나는 사람과 제품으로 그룹화하려고 시도했지만 어떻게 든 나는 곤경에 처하게되었다.Python Pandas DF - 다른 열의 해당 빈도가있는 그룹 열

다음은 작은 장난감 예입니다.

import pandas as pd 

# Create toy data frame 
A = [0,0,1,2,2,2,0] 
B = ['Person1','Person1','Person1','Person1','Person2','Person2','Person 2'] 
df = pd.DataFrame([A,B]).transpose() 
df.columns = ['cat', 'per'] 

# Desired Output 

      Cat0 Cat1 Cat2 
Person 1  2  1  1 
Person 2  1  0  2 

답변

2

먼저 값을 문자열 cat을 추가 할 수 있지만 astype에 의해 strint 캐스팅해야합니다. 그런 다음 pivot_table를 사용하고 (pandas0.18.0 새로운) rename_axis 마지막 :

import pandas as pd 

# Create toy data frame 
A = [0,0,1,2,2,2,0] 
B = ['Person1','Person1','Person1','Person1','Person2','Person2','Person2'] 
df = pd.DataFrame([A,B]).transpose() 
df.columns = ['cat', 'per'] 

print (df) 
    cat  per 
0 0 Person1 
1 0 Person1 
2 1 Person1 
3 2 Person1 
4 2 Person2 
5 2 Person2 
6 0 Person2 

df['cat'] = 'cat' + df.cat.astype(str) 
df = df.pivot_table(index='per', columns='cat', aggfunc=len,fill_value=0) 

df = df.rename_axis(None).rename_axis(None, axis=1) 
#if use older pandas as 0.18.0 
#df.columns.name= None 
#df.index.name= None 

print (df) 
     cat0 cat1 cat2 
Person1  2  1  1 
Person2  1  0  2 
관련 문제