import pandas as pd
import seaborn as sns
#titanic 데이터셋에서 age, sex, 등 5개 열을 선택하여 데이터프레임 만들기
titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age','sex','class','fare','survived']]
print('승객 수 : ', len(df))
display(df.head())
# Class 열을 기준으로 분할( 1개 열을 기준)
grouped = df.groupby(['class'])
print(grouped)
list(grouped)
#그룸 객체를 iteration 으로 출력 : head() 메소드로 첫 5행만 출력
for key, group in grouped:
print('* key:', key)
print('* number:', len(group))
print(group.head())
# 연산 메소드 적용
average = grouped.mean()
print(average)
stat = grouped.max()
stat
#개별 그룸 선택하기
group3 = grouped.get_group('Third')
print(group3.head())
group3.describe()
#class 열 sex열을 기준으로 분할(여러 열을 기준으로 분할)
grouped_two = df.groupby(['class','sex'])
# grouped_two 그룹 객체를 iteration 으로 출력
for key, group in grouped_two:
print('* key:',key)
print('* number:',len(group))
display(group.head())
# grouped_two 그룹 객체를 연산메소드 적용
average_two = grouped_two.mean()
print(average_two)
df.corr()
import pandas as pd
import seaborn as sns
#titanic 데이터셋에서 age, sex등 5개 열을 선택하여 데이터프레임 만들기
titanic = sns.load_dataset('titanic')
df = titanic.loc[:,['age','sex','class','fare','survived']]
#class 열을 기준으로 분할
grouped = df.groupby(['class'])
#각 그룹에 대한 모든 열의 표준편차를 집계하여 데이터프레임으로 전환
# 각 그룹에 대한 모든 열의 표준편차를 집계하여 데이터프레임으로 변환
std_all = grouped.std() # 표준편차를 그룹으로 저장
display(std_all)
print(type(std_all))
# 각 그룹에 대한 fare 열의 표준편차를 집계하여 시리즈로 반환
std_fare = grouped.fare.std()
display(std_fare)
print(type(std_fare))
# 그룹 전체에 agg() 메소드 적용 - 사용자 정의 함수를 인수로 전달
def min_max(x): # 최대값-최소값
return x.max() - x.min()
# 각 그룹의 최대값과 최소값 차이를 계산하여 그룹별로 집계
agg_minmax = grouped.agg(min_max)
print(agg_minmax.head())
# 여러 함수를 각 열에 동일하게 적용하여 집계
agg_all = grouped.agg(['min','max'])
display(agg_all.head())
('fare'는 'min', 'max', 'age'는 'mean')
#각 열마다 다른 함수를 적용하여 집계
agg_sep=grouped.agg({'fare':['min','max'],'age':'mean'})
print(agg_sep.head())
import pandas as pd
import seaborn as sns
#titanic 데이터셋에서 age, sex등 5개 열을 선택하여 데이터프레임 만들기
titanic = sns.load_dataset('titanic')
df = titanic.loc[:,['age','sex','class','fare','survived']]
#class 열을 기준으로 분할
grouped = df.groupby(['class'])
# 데이터 개수가 200개 이상인
grouped_filter = grouped.filter(lambda x : len(x) >=200) # 그룹의 길이가 200 이상인 것을 조건으로 filtering 하라는 의미
display(grouped_filter.head())
print(type(grouped_filter))
#age 열의 평균이 30보다 작은 그룹만을 필터링 하여 데이터프레임으로 반환.
age_filter = grouped.filter(lambda x : x.age.mean()<30)
print(age_filter.head())
print()
print(type(age_filter))
titanic = sns.load_dataset('titanic')
df = titanic.loc[:,['age','sex','class','fare','survived']]
grouped = df.groupby(['class'])
# 집계 : 각 그룹별 요약 통계정보를 집계
agg_grouped = grouped.apply(lambda x : x.describe())
display(agg_grouped)
def z_score(df):
return (df-df.mean()) / df.std()
age_zscore = grouped.age.apply(z_score) #기본값 axis=0
print(age_zscore.head())
from scipy.stats import zmap
import numpy as np
test = np.array([-0.33, -0.31, 0.55, 0.05, 0.93])
ctrl = np.array([[-0.65, 1.09, -1.67, -0.32, 1.26],
[0.39, 0.68, -0.28, -0.75, -0.72]])
zmap(test,ctrl)
test2 = np.expand_dims(test, axis=0)
test2 = np.concatenate((test2, ctrl))
zmap(test2,ctrl)
# z = (x - x.mean(axis=0)) / x.std(axis=0)
# 필터링 : age 열의 데이터 평균이 30보다 작은 그룹만을 필터링하여 출력!!!!!!!!
age_filter = grouped.apply(lambda x : x['age'].mean() < 30)
display(age_filter) # First 만 30보다 크기 때문에 False
for x in age_filter.index:
if age_filter[x]==True:
age_filter_df = grouped.get_group(x)
display(age_filter_df.head())
import pandas as pd
import seaborn as sns
#titanic 데이터 셋에서 age, sex등 5개 열을 선택하여 데이터프레임 만들기
titanic = sns.load_dataset('titanic')
df = titanic.loc[:,['age','sex','class','fare','survived']]
#class 열을 기준으로 분할
grouped = df.groupby(['class'])
# 그룹 객체에 연산 메서드 적용
gdf = grouped.mean()
print(gdf)
print()
print(type(gdf))
#Class 값이 first 인 행을 선택하여 출력
print(gdf.loc['First'])
import pandas as pd
import seaborn as sns
# IPython 디스플레이 설정 변경
pd.set_option('display.max_columns',10) #출력할 최대 열의 개수
pd.set_option('display.max_colwidth',10) #출력할 열의 너비
# titanic 데이터셋에서 age, sex 등 5개 열을 선택하여 데이터프레임 만들기
titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age','sex','class','fare','survived']]
display(df.head())
# 행, 열, 값, 집계에 사용할 열을 1개씩 지정 - 평균집계
pdf1 = pd.pivot_table(df, # 피벗할 데이터프레임
index='class', # 행 위치에 들어갈 열
columns='sex', # 열 위치에 들어갈 열
values='age', # 데이터로 사용할 열
aggfunc='mean') # 데이터 집계 함수
print(pdf1.head())
pdf2 = pd.pivot_table(df, # 피벗할 데이터프레임
index='class', # 행 위치에 들어갈 열
columns='sex', # 열 위치에 들어갈 열
values='survived', # 데이터로 사용할 열
aggfunc=('mean','sum')) # 데이터 집계 함수
display(pdf2.head())