+2 votes
in Programming Languages by (73.2k points)
Is there any Pythonic approach to calculate the square root of all elements of a Pandas DataFrame?

1 Answer

+1 vote
by (346k points)
selected by
 
Best answer

You can use transform() function of pandas with 'sqrt' as 'func' or a lamda function for square root as 'func'.

Approach 1: Using lambda function

>>> df
   c1  c2
0   1  25
1   4  36
2   9  49
3  16  64
>>> df.transform(lambda x:x**0.5)
    c1   c2
0  1.0  5.0
1  2.0  6.0
2  3.0  7.0
3  4.0  8.0
>>> df.transform(lambda x:x**0.5).astype(int)
   c1  c2
0   1   5
1   2   6
2   3   7
3   4   8

Approach 2: using sqrt function

>>> df.transform('sqrt')
    c1   c2
0  1.0  5.0
1  2.0  6.0
2  3.0  7.0
3  4.0  8.0
>>> df.transform('sqrt').astype(int)
   c1  c2
0   1   5
1   2   6
2   3   7
3   4   8


...