Dùng DataFrame.apply(func, axis=1) để áp dụng hàm cho từng hàng (row). axis=1 nghĩa là duyệt theo hàng (mặc định axis=0 là cột).
Cách 1: Lambda function
import pandas as pd
df = pd.DataFrame([
(10, 3, 13),
(0, 42, 11),
(26, 52, 1)
], columns=list('xyz'))
print("Ma trận gốc:")
print(df)
# Cộng 10 cho mỗi phần tử trong hàng
new_df = df.apply(lambda row: row + 10, axis=1)
print("\nMa trận sau khi +10:")
print(new_df)
Kết quả
Ma trận gốc:
x y z
0 10 3 13
1 0 42 11
2 26 52 1
Ma trận sau khi +10:
x y z
0 20 13 23
1 10 52 21
2 36 62 11
Cách 2: User-defined function
def square_data(x):
return x * x
df = pd.DataFrame([
(10, 3, 13),
(0, 42, 11),
(26, 52, 1)
], columns=list('xyz'))
new_df = df.apply(square_data, axis=1)
print(new_df)
Kết quả
x y z 0 100 9 169 1 0 1764 121 2 676 2704 1
Lưu ý hiệu năng
apply(axis=1)chạy loop Python → chậm trên DataFrame lớn.- Ưu tiên vectorized operations (numpy/pandas native) khi có thể:
# Thay vì apply(lambda row: row + 10, axis=1) df + 10 # Vectorized, nhanh hơn rất nhiều # Thay vì apply(square_data, axis=1) df ** 2 # Vectorized
Kết luận
df.apply(func, axis=1) áp dụng hàm cho từng hàng. Dùng cho logic phức tạp không vectorized được. Ưu tiên toán tử vectorized cho phép tính đơn giản.