2

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 Answer 1

1

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

2 Comments

But can you do it using DataFrame.transform because In the course that I was using he used DataFrame.transform only
I think not possible here what you need by one transform, need 2 times and concat

Your Answer

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