Skip to content

Instantly share code, notes, and snippets.

@84adam
Created June 10, 2022 23:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 84adam/29ff5fd1286a30d904540bf78e37f883 to your computer and use it in GitHub Desktop.
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.
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
@84adam
Copy link
Author

84adam commented Jun 10, 2022

Example Output:

                        input1                    output1          output2
| id | First Name | Birth Year | Favorite Color |     Age | Age Group      |
| 1  | Mary       | 1930       | Blue           |      92 | Ancient        |
| 2  | Harry      | 1940       | Red            |      82 | Still Kickin'  |
| 3  | Larry      | 1950       | Green          |      72 | Old            |
| 4  | Fairy      | 1960       | Pink           |      62 | Arnold Palmer  |
| 5  | Dairy      | 1970       | Orange         |      52 | Young at Heart |

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment