Quantcast
Channel: Recent Gists from 84adam
Viewing all articles
Browse latest Browse all 34

Apply a function to one column and assign the output to two pandas dataframe columns.

$
0
0
pandas-one-in-two-out-apply.py
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

Viewing all articles
Browse latest Browse all 34

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>