0

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?

3
  • 1
    Will help this answer? Commented Aug 12, 2021 at 19:55
  • I am not sure if you are calculating the new column values based on your existing df values Commented Aug 12, 2021 at 19:56
  • I am, I didn't show the process of doing that in the question in order to simplify it Commented Aug 12, 2021 at 19:58

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.