Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking a tuple on multiple columns of a dataframe from Series.apply

I came across this problem at work today and I would like to know if there is an efficient way to do this.

Basically I have a dataframe which look like this

df = pd.DataFrame([1,2,3], columns = ['a'])

I also have a function that returns a tuple. (Make note that this is only a minimal example, my problem is different)

compute = lambda x: (2*x, 3*x)

I need to find a way to do something that would ideally look like this:

(df['b'], df['c']) = df['a'].apply(compute)

Unfortunately, this syntax doesn't work and I can't wrap my head around another way to do it.

The only similar problem is this , but the solution seems really 'hacky' and I am convinced there is a better way to do it.

Thank you!!

like image 348
Tommy-Xavier Robillard Avatar asked Oct 28 '25 01:10

Tommy-Xavier Robillard


1 Answers

IIUC, you can try with:

compute = lambda x: (2*x, 3*x)
df[['b','c']]=pd.DataFrame(df.a.apply(compute).tolist()) #thanks harvpan
#df[['b','c']]=pd.DataFrame(df.a.apply(compute).values.tolist())
print(df)

   a  b  c
0  1  2  3
1  2  4  6
2  3  6  9
like image 78
anky Avatar answered Oct 30 '25 23:10

anky