In [1]:
import pandas as pd
import seaborn as sns
In [2]:
df: pd.DataFrame = sns.load_dataset('titanic')
df.head(2)
Out[2]:
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
In [3]:
df = df.loc[:, ['age', 'fare']]
df.head()
Out[3]:
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

2.1. 인자 하나(Series의 각 원소) 받는 함수¶

In [4]:
def add_10(x: float) -> float:
    return x + 10
In [5]:
sr1 = df['age'].apply(add_10)
sr1.head()
Out[5]:
0    32.0
1    48.0
2    36.0
3    45.0
4    45.0
Name: age, dtype: float64

2.2. 인자 여러 개 (Series의 각 원소 + 추가 인자) 받는 함수¶

In [6]:
def add_two_obj(x: float, n: int) -> float:
    return x + n
In [7]:
sr2: pd.Series = df['age'].apply(add_two_obj, n=10)  # 추가 인자 명시
sr2.head()
Out[7]:
0    32.0
1    48.0
2    36.0
3    45.0
4    45.0
Name: age, dtype: float64

2.3. lambda 사용¶

In [8]:
sr3: pd.Series = df['age'].apply(lambda x: x + 10)
sr3.head()
Out[8]:
0    32.0
1    48.0
2    36.0
3    45.0
4    45.0
Name: age, dtype: float64