Home > Software design >  pandas - running into problems setting multiple columns using results from pd.apply()
pandas - running into problems setting multiple columns using results from pd.apply()

Time:10-03

I have a function that returns tuples. When I apply this to my pandas dataframe using pd.apply() function, the results look this way.

enter image description here

The Date here is an index and I am not interested in it. I want to create two new columns in a dataframe and set their values to the values you see in these tuples.

How do I do this? I tried the following:

enter image description here

This errors out citing mismatch between expected and available values. It is seeing these tuples as a single entity, so those two columns I specified on the left hand side are a problem. Its expecting only one.

And what I need is to break it down into two parts that can be used to set two different columns.

Whats the correct way to achieve this?

CodePudding user response:

use zip

orders['a'], orders['b'] = zip(*df['your_column'])

CodePudding user response:

Make your function return a pd.Series, this will be expanded into a frame.

orders.apply(lambda x: pd.Series(myFunc(x)), axis=1)
  • Related