How To Add/insert Output Of A Function Call That Returns Multiple Fields, As New Columns Into Pandas Dataframe?
How to add/insert output of a function call that returns multiple fields, as new columns into Pandas dataframe ? Sample code & data: from pandas import DataFrame People_List =
Solution 1:
Although you can apply
, best is to use vectorized functions (see When should I (not) want to use pandas apply() in my code?). Your logic can be simplified as below:
print (df.assign(title=np.where(df["First_Name"].eq("Maria"), "Ms", "Mr"),
birth_year=pd.Timestamp.now().year-df["Age"])) # or 2020-df["Age"]
First_Name Last_Name Age title birth_year
0 Jon Smith 21 Mr 1999
1 Mark Brown 38 Mr 1982
2 Maria Lee 42 Ms 1978
3 Jill Jones 28 Mr 1992
4 Jack Ford 55 Mr 1965
Solution 2:
Here are two ways, apply and create the new columns
df[['title', 'birth_year']] = pd.DataFrame(df.apply(getTitleBirthYear, axis=1).tolist())
df[['title', 'birth_year']] = df.apply(getTitleBirthYear, axis=1, result_type='expand')
First_Name Last_Name Age title birth_year
0 Jon Smith 21 Mr 1999
1 Mark Brown 38 Mr 1982
2 Maria Lee 42 Ms 1978
3 Jill Jones 28 Mr 1992
4 Jack Ford 55 Mr 1965
Post a Comment for "How To Add/insert Output Of A Function Call That Returns Multiple Fields, As New Columns Into Pandas Dataframe?"