tedzz
tedzz

Reputation: 39

(Pandas) Set values for multiple columns at once using apply

I am using an apply method to determine the values for the three columns I am trying to create. The function that is responsible for calculating is calculate. It gives back the three values that are needed. The problem is how do I assign those three values to the columns. I tried doing something like this

def calculate(row):
    return 'column1_value', 'column2_value', 'column3_value'

df[['column1', 'column2', 'column3']] = df.apply(lambda row: calculate(row), axis=1)

That did not work, but is there a way that would allow assigning multiple values to multiple columns at once?

Upvotes: 0

Views: 790

Answers (1)

chatax
chatax

Reputation: 998

You could make a second DataFrame of your apply and concat the two column wise. This will create the new columns to your original dataframe

def calculate(row):
    return 'column1_value', 'column2_value', 'column3_value'

df2 = pd.DataFrame(list(df.apply(calculate, axis=1)), columns=['column1', 'column2', 'column3'])
df = pd.concat([df, df2], axis=1)

Upvotes: 1

Related Questions