2017-04-19 5 views
0

사용자 ID별로 각 방문 횟수를 요약하는 새 테이블을 만드는 아래 SQL 쿼리가 있습니다. 이 데이터 프레임을 파이썬으로 어떻게 만들 수 있습니까?새로운 데이터 프레임 그룹화 및 요약 열을 만드는 Python

create table User_Visits_summary as 
select user_id, 
sum(case when visit_type = 1 then 1 else 0 end) as Type_One_Counts, 
sum(case when visit_type = 2 then 1 else 0 end) as Type_Two_Counts, 
sum(case when visit_type = 3 then 1 else 0 end) as Type_Three_Counts, 
count(*) as Total_Visits 
from user_visits 
group by user_id 
+0

/어떻게 데이타가 저장되는이 cheatsheet- 체크 아웃? 'user_visits'는 이미 파이썬에서 dataframe/numpy 배열 /리스트입니까? 또는 이미 파이썬에 연결된 SQL 데이터베이스에 저장되어 있습니까? Pandas의 최신 버전은 SQL 문 (http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html)을 직접 처리 할 수있는 기능이 있습니다. 그러나 SQL 문을 Pandas 인덱싱/집계 문으로 변환하는 것이 더 효율적 (더 빠름)합니다. – jberrio

+0

예, user_visits는 이미 파이썬의 데이터 프레임입니다. SQL이 무엇을 수행 하는지를 포착하는 User_Visits_summary라는 새로운 데이터 프레임을 만들고 싶습니다. – esteban

답변

0

아래 코드는 SQL 쿼리와 동일한 테이블을 만들어야합니다. 코드의 주석을 읽고 디버그 모드로 실행하여 각 코드 행의 기능을 더 잘 이해할 수 있습니다. 팬더의 기능에 대한 유용한 가이드를 들어,

https://github.com/pandas-dev/pandas/blob/master/doc/cheatsheet/Pandas_Cheat_Sheet.pdf

import pandas as pd 

# example dataset 
user_visits = pd.DataFrame({'user_id' :['A','A','A','A','A','B','B','B','B'], 
          'visit_type':[ 1, 1, 3, 3, 3, 2, 2, 2, 2] }) 

# This summary table already contains the data you want, but on 'long column' format 
User_Visits_summary = user_visits.groupby(['user_id','visit_type']).size().reset_index() 

# Here we pivot the table to get to your desired format 
User_Visits_summary = User_Visits_summary.pivot(index='user_id',columns='visit_type', values=0) 

# Calculate total from sub-totals in new column 
User_Visits_summary['Total_Visits'] = User_Visits_summary.sum(axis=1)  

# Some formatting 
User_Visits_summary.reset_index(inplace=True) 
User_Visits_summary.rename(columns={1:'Type_One_Counts', 
            2:'Type_Two_Counts', 
            3:'Type_Three_Counts'}, inplace=True) 

# Table ready 
print(User_Visits_summary) 
# ...too wide to paste... 
+0

완벽하게 작동했습니다! 감사! – esteban

+0

걱정할 필요가 없습니다 ... 대답이 만족 스러울 경우 대답을 대답으로 표시하십시오. 고마워 – jberrio