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 19991 Mark Brown 38 Mr 19822 Maria Lee 42 Ms 19783 Jill Jones 28 Mr 19924 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_NameLast_NameAgetitlebirth_year0JonSmith21Mr19991MarkBrown38Mr19822MariaLee42Ms19783JillJones28Mr19924JackFord55Mr1965
Post a Comment for "How To Add/insert Output Of A Function Call That Returns Multiple Fields, As New Columns Into Pandas Dataframe?"