Mô tả bài toán
Cho Series số thực:
0 1.3 1 2.6 2 3.9 3 4.8 4 5.6
Yêu cầu: Làm tròn tất cả phần tử theo quy tắc làm tròn chuẩn (round half to even). Kết quả:
0 1.0 1 3.0 2 4.0 3 5.0 4 6.0
Giải pháp 1: Dùng phương thức .round() (khuyên dùng)
Pandas Series có sẵn phương thức round() thực hiện vector hóa.
import pandas as pd
l = [1.3, 2.6, 3.9, 4.8, 5.6]
data = pd.Series(l)
print("Series gốc:")
print(data)
rounded = data.round()
print("\nSau khi làm tròn (.round()):")
print(rounded)
Giải pháp 2: Duyệt vòng lặp với round() built-in
Dùng round() của Python trên từng phần tử (trả về int).
import pandas as pd
l = [1.3, 2.6, 3.9, 4.8, 5.6]
data = pd.Series(l)
ls = []
for i, j in data.items():
ls.append(round(j)) # round() built-in trả về int
result = pd.Series(ls)
print("\nSau khi làm tròn (vòng lặp + round()):")
print(result)
Đầu ra so sánh
--- .round() (float) --- 0 1.0 1 3.0 2 4.0 3 5.0 4 6.0 dtype: float64 --- round() built-in (int) --- 0 1 1 3 2 4 3 5 4 6 dtype: int64
Lưu ý: Series.round() giữ kiểu float, round() Python trả về int. Cách 1 hiệu quả hơn cho dữ liệu lớn.