본문 바로가기
파이썬/파이썬 pandas

[pandas] 그룹별 데이터 집계하기 groupby

by Merware 2023. 5. 15.
import pandas as pd
df = pd.read_csv('data/titanic.csv')
df = df[['Survived','Pclass','Sex','Age','Embarked']]
df = df.dropna()
df.head()

"""
Survived	Pclass	Sex	Age	Embarked
0	0	3	male	22.0	S
1	1	1	female	38.0	C
2	1	3	female	26.0	S
3	1	1	female	35.0	S
4	0	3	male	35.0	S
"""

df.info()

"""
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1044 entries, 0 to 1306
Data columns (total 5 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   Survived  1044 non-null   int64  
 1   Pclass    1044 non-null   int64  
 2   Sex       1044 non-null   object 
 3   Age       1044 non-null   float64
 4   Embarked  1044 non-null   object 
dtypes: float64(1), int64(2), object(2)
memory usage: 48.9+ KB

 

그룹의 통계값 계산하기

  • df.groupby(그룹기준컬럼).통계적용컬럼.통계함수
  • count() : 누락값을 제외한 데이터 수
  • size() : 누락값을 포함한 데이터 수
  • mean() : 평균
  • sum() : 합계
  • std() : 표준편차
  • min() : 최소값
  • max() : 최대값
  • sum() : 전체 합

객실등급별 생존 통계

# 객실등급(Pclass)별 승선자 수를 구한 결과를 데이터프레임 df1로 만들기
df1 = df.groupby('Pclass').Survived.count().to_frame()
df1

"""
	Survived
Pclass	
1	282
2	261
3	501
# 객실등급(Pclass)별 생존자 수를 구한 결과를 데이터프레임 df2로 만들기
df2 = df.groupby('Pclass').Survived.sum().to_frame()
df2 

"""
	Survived
Pclass	
1	168
2	112
3	135
# 객실등급(Pclass)별 생존율 구한 결과를 데이터프레임 df3으로 만들기
df3 = df.groupby('Pclass').Survived.mean().to_frame()
df3

"""
	Survived
Pclass	
1	0.595745
2	0.429119
3	0.269461
# 객실등급(Pclass)별 탑승자수, 생존자수, 생존율 데이터프레임을 df4로 만들기
df4 = pd.concat([df1,df2,df3], axis=1)
df4.columns=['승선자수','생존자수','생존율']
df4

"""
	승선자수	생존자수	생존율
Pclass			
1	282	168	0.595745
2	261	112	0.429119
3	501	135	0.269461

 

성별 생존 통계

# 성별 승선자 수 데이터프레임을 df5로 만들기
df5 = df.groupby('Sex').Survived.count().to_frame()
df5

"""
	Survived
Sex	
female	386
male	658
# 성별 생존자 수 데이터프레임을 df6으로 만들기
df6 = df.groupby('Sex').Survived.sum().to_frame()
df6

"""
	Survived
Sex	
female	322
male	93

 

# 성별 생존율 데이터프레임을 df7로 만들기
df7 = df.groupby('Sex').Survived.mean().to_frame()
df7

"""
	Survived
Sex	
female	0.834197
male	0.141337