개별 원소에 함수 매핑

매핑 함수로 보통함수와 Lambda함수 모두 사용할 수 있다.

apply() : 시리즈 원소에 함수 매핑

apply() 함수를 사용하면 시리즈의 모든 원소에 매핑 함수를 적용시킨다. 같은 크기의 시리즈를 반환한다.

import seaborn as sns

titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age', 'fare']]

df['ten'] = 10
print("df head :")
print(df.head())

def add_10(n):
    return n + 10

def add_two_obj(a, b):
    return a+b

sr1 = df['age'].apply(add_10)
print("sr1 head : ")
print(sr1.head())

sr2 = df['age'].apply(add_two_obj, b=10)
print("sr2 head : ")
print(sr2.head())

sr3 = df['age'].apply(lambda x: add_10(x))
print("sr3 head : ")
print(sr3.head())
df head :
    age     fare  ten
0  22.0   7.2500   10
1  38.0  71.2833   10
2  26.0   7.9250   10
3  35.0  53.1000   10
4  35.0   8.0500   10
sr1 head : 
0    32.0
1    48.0
2    36.0
3    45.0
4    45.0
Name: age, dtype: float64
sr2 head :
0    32.0
1    48.0
2    36.0
3    45.0
4    45.0
Name: age, dtype: float64
sr3 head :
0    32.0
1    48.0
2    36.0
3    45.0
4    45.0
Name: age, dtype: float64

applymap() : 데이터프레임 원소에 함수 매핑

데이터프레임에는 applymap() 함수를 사용하면된다.

import seaborn as sns

titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age', 'fare']]

def add_10(n):
    return n + 10

print("before")
print(df.head())
print("after")
df_map = df.applymap(add_10)
print(df_map.head())
before
    age     fare
0  22.0   7.2500
1  38.0  71.2833
2  26.0   7.9250
3  35.0  53.1000
4  35.0   8.0500
after
    age     fare
0  32.0  17.2500
1  48.0  81.2833
2  36.0  17.9250
3  45.0  63.1000
4  45.0  18.0500

시리즈 객체에 함수 매핑

apply(axis = 0) : 데이터프레임의 각 열에 함수 매핑

데이터프레임에 apply(axis = 0) 메서드를 적용하면 모든 열을 하나씩 분리하여 매핑 함수의 인자로 각 열(시리즈)가 전달된다. 매핑 함수에 따라 반환되는 객체의 종류가 다르다.

import seaborn as sns

titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age', 'fare']]

# 사용자 함수 정의

def missing_value(series):
    return series.isnull()  # boolen 반환

result = df.apply(missing_value, axis=0)
print(result.head())
print(type(result))
     age   fare
0  False  False
1  False  False
2  False  False
3  False  False
4  False  False
<class 'pandas.core.frame.DataFrame'>

위의 예제에서는 Series를 입력받아 Series를 반환했다. 아래에서는 Series를 입력받아 float64로 반환된다.

import seaborn as sns

titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age', 'fare']]

# 사용자 함수 정의

def min_max(x):
    return x.max() - x.min()
# 하나의 Series를 입력받아 하나의 값을 반환한다.

result = df.apply(min_max)
print(result)
age      79.5800
fare    512.3292
dtype: float64