Write a program in Python to print the power of all the elements in a given series

Computing the power of each element in a Pandas Series means raising each element to itself (xx). This tutorial demonstrates three different approaches to achieve this operation.

Input − Assume, you have a series,

0    1
1    2
2    3
3    4

Output − And, the result for the power of all elements in a series is,

0      1
1      4
2     27
3    256

Using transform() with Lambda Function

The transform() method applies a function to each element of the series. We use a lambda function to calculate xx for each element ?

import pandas as pd

data = pd.Series([1, 2, 3, 4])
print("Original Series:")
print(data)

result = data.transform(lambda x: x**x)
print("\nPower of elements:")
print(result)
Original Series:
0    1
1    2
2    3
3    4
dtype: int64

Power of elements:
0      1
1      4
2     27
3    256
dtype: int64

Using Loop with math.pow()

This approach iterates through each element using items() and applies math.pow() to calculate the power ?

import pandas as pd
import math as m

data = pd.Series([1, 2, 3, 4])
power_list = []

for index, value in data.items():
    power_list.append(m.pow(value, value))

result = pd.Series(power_list)
print("Power of elements:")
print(result)
Power of elements:
0      1.0
1      4.0
2     27.0
3    256.0
dtype: float64

Using apply() Method

The apply() method provides another clean way to perform element-wise operations ?

import pandas as pd

data = pd.Series([1, 2, 3, 4])
result = data.apply(lambda x: x**x)
print("Power of elements:")
print(result)
Power of elements:
0      1
1      4
2     27
3    256
dtype: int64

Comparison

Method Performance Return Type Best For
transform() Fast Same as input Vectorized operations
Loop with math.pow() Slower Float values Complex operations
apply() Fast Same as input General transformations

Conclusion

Use transform() or apply() with lambda functions for efficient power calculations in Pandas Series. The loop approach offers more control but is less efficient for large datasets.

Updated on: 2026-03-25T15:50:55+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements