Created
June 10, 2022 23:07
-
-
Save 84adam/29ff5fd1286a30d904540bf78e37f883 to your computer and use it in GitHub Desktop.
Apply a function to one column and assign the output to two pandas dataframe columns.
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
import pandas as pd | |
# 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 | |
def generation(birth_year): | |
age = 2022 - birth_year | |
if 0 < age < 50: | |
age_group = 'Young' | |
elif 50 < age < 60: | |
age_group = 'Young at Heart' | |
elif 60 < age < 70: | |
age_group = 'Arnold Palmer' | |
elif 70 < age < 80: | |
age_group = 'Old' | |
elif 80 < age < 90: | |
age_group = "Still Kickin'" | |
else: | |
age_group = "Ancient" | |
return age, age_group | |
# APPLY THE FUNCTION TO ONE COLUMN, ASSIGNING THE OUTPUT TO TWO NEW COLUMNS | |
df[['Age','Age Group']] = df.apply(lambda x: generation(x['Birth Year']), axis=1, result_type='expand') | |
df |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Output: