PYTHON/machine_learning

판다스

죠으니 2022. 1. 22. 19:49

▶판다스의 주요 구성 요소 :

   DataFrame(2차원 데이터 셋), Series(1개의 column값으로만 구성된 1차원 데이터 셋), Index

info() : DataFrame내의 컬럼명, 데이터 타입, Null건수, 데이터 건수 정보를 제공.

describe() : 데이터값들의 평균, 표준편차, 4분위 분포도를 제공. 숫자형 컬럼들에 대해서 해당 정보를 제공.

value_counts()

   동일한 개별 데이터 값이 몇건이 있는지 정보를 제공.

   즉 개별 데이터값의 분포도를 제공합니다.

   주의할 점은 value_counts()는 Series객체에서만 호출 될 수 있으므로 반드시 DataFrame을 단일 컬럼으로 입력하여       Series로 변환한 뒤 호출합니다.

sort_values() : by=정렬컬럼, ascending=True 또는 False로 오름차순/내림차순으로 정렬

  ex)  titanic_df.sort_values(by='Pclass', ascending=True)

▶DataFrame을 리스트로 변환 : df_dict.values.tolist()

  DataFrame을 딕셔너리로 변환 : df_dict.to_dict('list')

 

참고 : DataFrame.to_dict(orient='dict') 와 같이 to_dict() 의 orient 인자의 default 값(기본값)은 'dict' 이다.

        그런데 이렇게 변환하면 dictionary 변환된 값의 key, value가 key는 column명인데, value가 dictionary 이고,

        이 value dictionary에는 다시 index와 column 값으로 되어 있다.

        보다 명확하게 Dictionary 형태로 변환하는 것은 to_dict(orient='list') 이기 때문에 'list'값을 입력 했습니다.

        둘다 딕셔너리 형태로 바꾸는데는 상관이 없지만

        일반적으로 orient='dict' 보다는 'list'가 더 직관적인 Dictionary형태로 변환해주므로 list를 적용했습니다.

 

[ ]를 이용하여 임의로 Index의 값을 변경할 수는 없다.

DataFrame 및 Series에 reset_index( ) 메서드를 수행하면 새롭게 인덱스를 연속 숫자 형으로 할당하며 기존 인덱스는    ‘index’라는 새로운 컬럼 명으로 추가

 

넘파이에서 [ ] 연산자는 행의 위치, 열의 위치, 슬라이싱 범위 등을 지정해 데이터를 가져올 수 있었습니다.

   하지만 DataFrame 바로 뒤에 있는 ‘[ ]’ 안에 들어갈 수 있는 것은 컬럼 명 문자(또는 컬럼 명의 리스트 객체),               또는 인덱스로 변환 가능한 표현식입니다.

 

▶DataFrame의 [ ] 내에 숫자 값을 입력할 경우 오류가 발생한다고 했는데,

   Pandas의 Index 형태로 변환가능한 표현식은 [ ] 내에 입력할 수 있습니다.  
   ex) titanic_df의 처음 2개 데이터를 추출하고자  titanic_df [ 0:2 ] 와 같은 슬라이싱을 이용하면 정확히 원하는 결과를          반환해 줍니다. 

ix[] : 명칭 기반과 위치 기반 인덱싱 모두를 제공.

▶다 같은 데이터를 찾는다.

   titanic_df[titanic_df['Age'] > 60][['Name','Age']].head(22)

   titanic_df[['Name','Age']][titanic_df['Age'] > 60].head(22)

   titanic_df.loc[titanic_df['Age'] > 60, ['Name','Age']].head(22)

 

논리 연산자로 결합된 조건식도 불린 인덱싱으로 적용 가능.

   titanic_df[ (titanic_df['Age'] > 60) & (titanic_df['Pclass']==1) & (titanic_df['Sex']=='female')]

 

□ Aggregation 함수 및 GroupBy 적용

▶titanic_df.count()  ←  NaN 값은 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)

Age     21205.1700
Fare    28693.9493
dtype: float64

   titanic_df[['Age', 'Fare']].count()

Age     714
Fare    891
dtype: int64

groupby( ) : by 인자에 Group By 하고자 하는 컬럼을 입력, 여러개의 컬럼으로 Group by 하고자 하면 [ ] 내에 해당 컬럼명을 입력. DataFrame에 groupby( )를 호출하면 DataFrameGroupBy 객체를 반환.

   titanic_groupby = titanic_df.groupby('Pclass').count()

   titanic_groupby = titanic_df.groupby(['Pclass','SibSp']).count()

 

▶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])

 

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

   agg_format={'Age':'max', 'SibSp':'sum', 'Fare':'mean'}
   titanic_df.groupby('Pclass').agg(agg_format)

 isna( ) : 주어진 컬럼값들의 NaN인지 True/False 값을 반환 (NaN이면 True)

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

   titanic_df.isna( ).sum( )

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'].fillna(넣고 싶은 것)

 

□ apply lambda 식으로 데이터 가공

▶일반 함수

   def get_square(a):
    return a**2

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

3의 제곱은: 9

▶파이썬 lambda식

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

3의 제곱은: 9

▶a=[1,2,3]
   squares = map(lambda x : x**2, a)
   list(squares)

[1, 4, 9]

판다스에 apply lambda 식 적용.

   titanic_df['Name_len']= titanic_df['Name'].apply(lambda x : len(x))

   titanic_df['Child_Adult'] = titanic_df['Age'].apply(lambda x : 'Child' if x <=15 else 'Adult' )

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

   새로운 열 'Name_len', 'Child_Adult' 이 추가됨.

 

▶2차원 데이터 핸들링을 위해서는 판다스를 사용하는게 좋음!

 

'PYTHON > machine_learning' 카테고리의 다른 글

선형회귀 _ bike-sharing-demand  (0) 2022.01.30
머신 러닝 지도 학습 프로세스  (0) 2022.01.26
분류(Classification)  (0) 2022.01.26
회귀(Regression)  (0) 2022.01.26
넘파이 ndarray  (0) 2022.01.22