728x90
반응형

Aggregation 함수 및 GroupBy 적용

** Aggregation 함수 sum, max, min, count 집합연산**

import pandas as pd
titanic_df = pd.read_csv('titanic_train.csv')

 

## NaN 값은 count에서 제외
titanic_df.count()

PassengerId    891
Survived       891
Pclass         891
Name           891
Sex            891
Age            714
SibSp          891
Parch          891
Ticket         891
Fare           891
Cabin          204
Embarked       889
dtype: int64

 

특정 컬럼들로 Aggregation 함수 수행.

titanic_df[['Age', 'Fare']].mean(axis=1) # 열들 평균

0      14.62500
1      54.64165
2      16.96250
3      44.05000
4      21.52500
         ...   
886    20.00000
887    24.50000
888    23.45000
889    28.00000
890    19.87500
Length: 891, dtype: float64

 

titanic_df[['Age', 'Fare']].sum(axis=0) # 불러온 것은 '행'을 불러왔지만 '행들'을 연산한 것이라 실상 col 합

Age     21205.1700
Fare    28693.9493
dtype: float64

 

titanic_df[['Age', 'Fare']].count() # col당 row 개수 // null은 제외

Age     714
Fare    891
dtype: int64

 

groupby( ) 

by 인자에 Group By 하고자 하는 컬럼을 입력, 여러개의 컬럼으로 Group by 하고자 하면 [ ] 내에 해당 컬럼명을 입력.

DataFrame에 groupby( )를 호출하면 DataFrameGroupBy 객체를 반환. SQL과의 차이점 주목

titanic_groupby = titanic_df.groupby(by='Pclass')
print(type(titanic_groupby)) 
print(titanic_groupby)

# <class 'pandas.core.groupby.generic.DataFrameGroupBy'>
# <pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000014E7CF8BC70>

 

DataFrameGroupBy객체에 Aggregation함수를 호출하여 Group by 수행.

titanic_groupby = titanic_df.groupby('Pclass').count() # 인덱스명은 gb 된 pclass로 됨
titanic_groupby

	PassengerId	Survived	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
Pclass											
1	216	216	216	216	186	216	216	216	216	176	214
2	184	184	184	184	173	184	184	184	184	16	184
3	491	491	491	491	355	491	491	491	491	12	491

 

print(type(titanic_groupby))
print(titanic_groupby.shape) # 원래는 col이 12개인데 pclass가 index가 되면서 col이 11개가 됨
print(titanic_groupby.index) # index는 name 이 pclass

# <class 'pandas.core.frame.DataFrame'>
# (3, 11)
# Int64Index([1, 2, 3], dtype='int64', name='Pclass')

 

titanic_groupby = titanic_df.groupby(by='Pclass')[['PassengerId', 'Survived']].count() # 또 특정 col 만 모으기 가능  브레이킷
titanic_groupby

	PassengerId	Survived
Pclass		
1	216	216
2	184	184
3	491	491

 

titanic_df[['Pclass','PassengerId', 'Survived']].groupby('Pclass').count() 
# 순서 상관없음 // col 먼저 따지면 메모리 최소화하기도 // 기존이 된 pclass는 무조건 넣어줘야함

	PassengerId	Survived
Pclass		
1	216	216
2	184	184
3	491	491

 

titanic_df.groupby('Pclass')['Pclass'].count() # plass 만하고싶다면 gb[]보다는 value_count가 좋음
titanic_df['Pclass'].value_counts()

3    491
1    216
2    184
Name: Pclass, dtype: int64

 

RDBMS의 group by는 select 절에 여러개의 aggregation 함수를 적용할 수 있음.

Select max(Age), min(Age) from titanic_table group by Pclass

판다스는 여러개의 aggregation 함수를 적용할 수 있도록 agg( )함수를 별도로 제공

titanic_df.groupby('Pclass')['Age'].agg([max, min]) # 여러개를 .max().min()이 안되서  agg([ , ])로 수행

	max	min
Pclass		
1	80.0	0.92
2	70.0	0.67
3	74.0	0.42

 

딕셔너리를 이용하여 다양한 aggregation 함수를 적용

agg_format={'Age':'max', 'SibSp':'sum', 'Fare':'mean'} # 각컬럼에 각기 다른 함수를 부여하고 싶다면 dict으로 key 부여
titanic_df.groupby('Pclass').agg(agg_format)

	Age	SibSp	Fare
Pclass			
1	80.0	90	84.154687
2	70.0	74	20.662183
3	74.0	302	13.675550

 

Missing 데이터 처리하기

DataFrame의 isna( ) 메소드는 모든 컬럼값들이 NaN인지 True/False값을 반환함(NaN이면 True)

titanic_df.isna().head(3) # 모든 COL에 T/F 출력

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	False	False	False	False	False	False	False	False	False	False	True	False
1	False	False	False	False	False	False	False	False	False	False	False	False
2	False	False	False	False	False	False	False	False	False	False	True	False

 

아래와 같이 isna( ) 반환 결과에 sum( )을 호출하여 컬럼별로 NaN 건수를 구할 수 있습니다.

titanic_df.isna( ).sum( ) # NULL의 개수를 계산 VS COUNT와 반대

PassengerId      0
Survived         0
Pclass           0
Name             0
Sex              0
Age            177
SibSp            0
Parch            0
Ticket           0
Fare             0
Cabin          687
Embarked         2
dtype: int64

 

** fillna( ) 로 Missing 데이터를 인자로 대체하기 **

titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000') #NULL 이면 COOO으로 채워주줘
titanic_df.head(3)

	PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	1	0	3	Braund, Mr....	male	22.0	1	0	A/5 21171	7.2500	C000	S
1	2	1	1	Cumings, Mr...	female	38.0	1	0	PC 17599	71.2833	C85	C
2	3	1	3	Heikkinen, ...	female	26.0	0	0	STON/O2. 31...	7.9250	C000	S

 

titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())
titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')
titanic_df.isna().sum()

PassengerId    0
Survived       0
Pclass         0
Name           0
Sex            0
Age            0
SibSp          0
Parch          0
Ticket         0
Fare           0
Cabin          0
Embarked       0
dtype: int64

 

apply lambda // 함수 식으로 데이터 가공

파이썬 lambda 식 기본 // apply 함수에 lambda 결합, df, series에 레코드별 데이터 가공 기능,

보통은 일괄 데이터 가공이 속도면에서 빠르지만, 복잡한데이터 가공시 행별 apply lambda 이용

lambda x(입력 인자) : x**2(입력인자를 기반으로한 계산식이며 호출 시 계산 결과가 반환됨)

def get_square(a):
    return a**2

print('3의 제곱은:',get_square(3))

# 3의 제곱은: 9

 

lambda_square = lambda x : x ** 2
print('3의 제곱은:',lambda_square(3))

# 3의 제곱은: 9

 

a=[1,2,3]
squares = map(lambda x : x**2, a) # 입력값이 여러개면 map
list(squares)

# [1, 4, 9]

 

** 판다스에 apply lambda 식 적용 **

titanic_df['Name_len']= titanic_df['Name'].apply(lambda x : len(x)) # 이경우는 매우심플, 그냥 내장함수를 서도 되는 정도
titanic_df[['Name','Name_len']].head(3)


Name	Name_len
0	Braund, Mr....	23
1	Cumings, Mr...	51
2	Heikkinen, ...	22

 

titanic_df['Child_Adult'] = titanic_df['Age'].apply(lambda x : 'Child' if x <=15 else 'Adult' ) #함수처럼 자체 가공
titanic_df[['Age','Child_Adult']].head(10)

	Age	Child_Adult
0	22.000000	Adult
1	38.000000	Adult
2	26.000000	Adult
3	35.000000	Adult
4	35.000000	Adult
5	29.699118	Adult
6	54.000000	Adult
7	2.000000	Child
8	27.000000	Adult
9	14.000000	Child

 

titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : 'Child' if x<=15 else ('Adult' if x <= 60 else 
                                                                                  'Elderly'))
titanic_df['Age_cat'].value_counts()

Adult      786
Child       83
Elderly     22
Name: Age_cat, dtype: int64

 

def get_category(age):
    cat = ''
    if age <= 5: cat = 'Baby'
    elif age <= 12: cat = 'Child'
    elif age <= 18: cat = 'Teenager'
    elif age <= 25: cat = 'Student'
    elif age <= 35: cat = 'Young Adult'
    elif age <= 60: cat = 'Adult'
    else : cat = 'Elderly'
    
    return cat # 꼭 return을 해줘야함

titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : get_category(x)) # 함수처럼 호출리턴
titanic_df[['Age','Age_cat']].head()

	Age	Age_cat
0	22.0	Student
1	38.0	Adult
2	26.0	Young Adult
3	35.0	Young Adult
4	35.0	Young Adult

 

 

 

반응형

'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글

2-3. model selection || sklearn  (0) 2021.12.22
2-2. sklearn 내장 데이터 || iris  (0) 2021.12.22
2-1. iris || sklearn  (0) 2021.12.22
1-2. Pandas  (0) 2021.12.22
1-1. Numpy  (0) 2021.12.22

+ Recent posts