Mô tả bài toán
Cho Series: [1, 2, 3, 4].
Yêu cầu: Tính lũy thừa của mỗi phần tử cho chính nó (x^x). Kết quả: 1^1=1, 2^2=4, 3^3=27, 4^4=256.
Giải pháp 1: Dùng transform + lambda (khuyên dùng)
import pandas as pd
l = [1,2,3,4]
data = pd.Series(l)
print("Series gốc:")
print(data)
# Vector hóa với transform
result = data.transform(lambda x: x**x)
print("\nKết quả x^x (transform):")
print(result)
Giải pháp 2: Vòng lặp + math.pow
import pandas as pd
import math as m
l = [1,2,3,4]
data = pd.Series(l)
ls = []
for i, j in data.items():
ls.append(m.pow(j, j)) # Trả về float
result = pd.Series(ls)
print("\nKết quả (math.pow - float):")
print(result)
Giải pháp 3: Toán tử ** trực tiếp (nhanh nhất)
import pandas as pd
data = pd.Series([1,2,3,4])
# Cách 1: apply
result1 = data.apply(lambda x: x**x)
# Cách 2: Vector hóa numpy (nếu dữ liệu lớn)
import numpy as np
result2 = pd.Series(np.power(data.values, data.values), index=data.index)
print("apply:", result1.tolist())
print("np.power:", result2.tolist())
Đầu ra so sánh
--- transform/apply (int) --- 0 1 1 4 2 27 3 256 dtype: int64 --- math.pow (float) --- 0 1.0 1 4.0 2 27.0 3 256.0 dtype: float64
Lưu ý: transform và apply giữ kiểu int nếu input int. math.pow luôn trả về float. Với dữ liệu lớn, np.power nhanh nhất.