[Python.Pandas] DataFrame.apply, DataFrame.applymap

2020. 12. 21. 05:00Python과 머신러닝/Pandas 데이터 분석

0. 이전 포스트

 

[Python.Pandas] Lambda함수와 Map함수 이해하기 - Series.map

1. Lambda란? In [1]:def f1(x,y): return x+y In [2]:f1(1,2) Out[2]:3 In [3]:f2=lambda x,y:x+y In [4]:f2(1,2) Out[4]:3 Lambda란 함수를 한 줄로 표현하는 익명 함수 기법이다. lisp 언어에서 시작된 기법으..

coding-grandpa.tistory.com

 

[Python.Pandas] Map 함수 실전편 + .replace함수 사용하기

1. wget으로 데이터 다운로드하여 .unique로 데이터 종류 분석하기 In [1]:import wget url = 'https://raw.githubusercontent.com/rstudio/Intro/master/data/wages.csv' wget.download(url) Out[1]:'wages.csv'..

coding-grandpa.tistory.com

1. DataFrame.Apply - 하나의 Series가 아닌 전체 DataFrame에 함수를 적용하고 싶을 때

In [1]:from pandas import Series, DataFrame 
       import pandas as pd 
       import numpy as np

In [2]:df = pd.read_csv("wages.csv") 
       df.head()
Out[2]:
    earn            height  sex     race    ed  age
0   79571.299011    73.89   male    white   16  49
1   96396.988643    66.23   female  white   16  62
2   48710.666947    63.77   female  white   16  33
3   80478.096153    63.22   female  other   16  95
4   82089.345498    63.08   female  white   17  43

In [3]:df_info=df[['earn', 'height', 'age']] 
       df_info.head()
Out[3]:
    earn            height  age
0   79571.299011    73.89   49
1   96396.988643    66.23   62
2   48710.666947    63.77   33
3   80478.096153    63.22   95
4   82089.345498    63.08   43

In [4]:f1=lambda x:np.mean(x)

In [5]:df_info.apply(f1)
Out[5]:earn      32446.292622 
       height    66.592640 
       age       45.328499 
       dtype: float64

 

2. .apply를 통해서 여러 함수 적용하기

In [6]:def f2(x): 
           return Series([x.min(), x.max(), x.mean(), sum(x.isnull())], 
                         index=['min', 'max', 'mean', 'null'])
                         
In [7]:df_info.apply(f2)
Out[7]:
      earn           height      age
min   -98.580489     57.34000    22.000000
max   317949.127955  77.21000    95.000000
mean  32446.292622   66.59264    45.328499
null  0.000000	     0.00000     0.000000
  • 한 번에 여러 가지 데이터를 보고 싶다면 어떻게 할까?
  • 개별로 함수를 정의하고 apply로 따로 볼 수도 있지만, 위와 같이 여러 함수를 하나의 series로 반환하도록 본 함수를 정의한다면 (f2), 한 번의 apply를 통해 여러 통계 데이터를 볼 수 있다.
  • 한 번 이렇게 함수를 정의하면 DataFrame이 변경되어도 재사용할 수 있는 장점이 있다.

 

3. .applymap - Series별 통계 함수가 아닌 element-wise operatio을 위한 함수

In [8]:f3=lambda x:x//2
In [9]:df_info.applymap(f3).head()

Out[9]:
     earn       height  age
0    39785.0    36.0    24
1    48198.0    33.0    31
2    24355.0    31.0    16
3    40239.0    31.0    47
4    41044.0    31.0    21
  • .apply는 DataFrame에서 각 Series에 대해 함수를 적용하였다.
  • 그래서 키/나이/수입 등의 정보에 대한 평균 정보를 추출한 것이었다.
  • 그에 비해 .applymap 함수는, 해당 함수의 동작을 Element 별로 전부 적용하게 된다.
  • 그래서 통계 데이터가 나온다기 보다는, 각각의 값을 변경할 수 있게 된다.
  • Series 별로 평균, 표준편차를 구할 때는 .apply함수를 사용하고, 각 element 별로 표준화를 수행할 때는 .applymap을 통해서 DataFrame의 전체 데이터를 한 번에 변경할 수 있다.

 

4. 관련 포스트

 

[Python.Pandas] Built-in Function 이해하기 - .describe()

1. DataFrame.describe 및 데이터 초기 분석 In [1]:from pandas import Series, DataFrame import pandas as pd import numpy as np In [2]:df = pd.read_csv('wages.csv') df.head(2).T Out[2]: 0 1 earn 79571...

coding-grandpa.tistory.com

 

반응형