Passing multiple lambda functions in Pandas.DataFrame.transform in Python

Viewed 103

this is the code (in python)

import numpy as np
import pandas as pd
df_5 = pd.DataFrame({'A': range(3), 'B': range(1, 4)})
df_5.transform([lambda x: x**2, lambda x: x**3])

and see the DataFrame for reference

DataFrame

this is the output (It just does the 2nd thing lambda x: x**3)

My output

but I want it to look like this (where Both the columns have been both lambda x: x**2 and lambda x: x**3)

Correct output

so what changes should I make to the last line df_5.transform([lambda x: x**2, lambda x: x**3])

1 Answers

Use DataFrame.apply:

df = df_5.apply([lambda x: x**2, lambda x: x**3])
print (df)
         A                 B         
  <lambda> <lambda> <lambda> <lambda>
0        0        0        1        1
1        1        1        4        8
2        4        8        9       27

If transform is necessary:

df = pd.concat([df_5.transform([lambda x: x**2]), 
                df_5.transform([lambda x: x**3])],axis=1).sort_index(axis=1)
    
print (df)
         A                 B         
  <lambda> <lambda> <lambda> <lambda>
0        0        0        1        1
1        1        1        4        8
2        4        8        9       27
Related