Question
How do I create multiple new DataFrame columns using DataFrame.assign and apply
Test code:
import pandas as pd
import numpy as np
df = pd.DataFrame({"Cat":1,"Dog":2},index=["10/1/21","11/1/21"])
df
Cat Dog
10/1/21 1 2
11/1/21 1 2
Function
def catDog (x):
if x.Cat > x.Dog:
sound = "Meow"
if x.Dog > x.Cat:
sound = "Woof"
return (sound,sound[0])
Using apply
df2 = df.apply(catDog,axis=1, result_type='expand')
df2.columns = ["Sound","Letter"]
df2
Sound Letter
10/1/21 Woof W
11/1/21 Woof W
How do I get this desired output using something like DataFrame.assign similar to the following
Cat Dog Sound Letter
10/1/21 1 2 Woof W
11/1/21 1 2 Woof W
What have I tried?
I can manually assign without function
df = df.assign(Sound="Woof")
df = df.assign(Letter="W")
but I want to create any number of new columns using something similar to my (toy) catDog function.
dfanddf2usingpd.mergeorpd.concat. Or you could expand the retuned dataframe into the assign, e.g. withdf.assign(**df.apply(catDog,axis=1, result_type='expand'))df[['Sound', Letter']]= df.apply(catDog,axis=1, result_type='expand')if I'm understanding correctly and comment outdf2.columns = ["Sound","Letter"]. AlsocatDogfunction could just beif elsebut consider if they will ever be equal and what should be returned in that case.