pandas-one-in-two-out-apply.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
importpandasaspd | |
# MAKE UP SOME DATA | |
data= {'id': [1, 2, 3, 4, 5], | |
'First Name': ['Mary', 'Harry', 'Larry', 'Fairy', 'Dairy',], | |
'Birth Year': [1930,1940,1950,1960,1970], | |
'Favorite Color': ['Blue', 'Red', 'Green', 'Pink', 'Orange']} | |
# CREATE A DATAFRAME | |
df=pd.DataFrame.from_dict(data) | |
# DEFINE A FUNCION WITH ONE INPUT AND TWO OUTPUTS | |
defgeneration(birth_year): | |
age=2022-birth_year | |
if0<age<50: | |
age_group='Young' | |
elif50<age<60: | |
age_group='Young at Heart' | |
elif60<age<70: | |
age_group='Arnold Palmer' | |
elif70<age<80: | |
age_group='Old' | |
elif80<age<90: | |
age_group="Still Kickin'" | |
else: | |
age_group="Ancient" | |
returnage, age_group | |
# APPLY THE FUNCTION TO ONE COLUMN, ASSIGNING THE OUTPUT TO TWO NEW COLUMNS | |
df[['Age','Age Group']] =df.apply(lambdax: generation(x['Birth Year']), axis=1, result_type='expand') | |
df |