Mô tả bài toán
Cho Series hỗn hợp:
0 1 1 2 2 python 3 3 4 4 5 5 6 6.5 dtype: object
Yêu cầu: Đếm số phần tử kiểu integer, float, string. Kết quả: int=5, float=1, string=1.
Giải pháp 1: Lambda filter + type() (cách gốc)
import pandas as pd
ls = [1, 2, "python", 3, 4, 5, 6.5]
data = pd.Series(ls)
int_count = len(pd.Series(filter(lambda x: type(x) == int, data)))
float_count = len(pd.Series(filter(lambda x: type(x) == float, data)))
str_count = len(pd.Series(filter(lambda x: type(x) == str, data)))
print(f"integer count: {int_count}")
print(f"float count: {float_count}")
print(f"string count: {str_count}")
Giải pháp 2: Vector hóa với apply + type (hiệu quả hơn)
import pandas as pd
data = pd.Series([1, 2, "python", 3, 4, 5, 6.5])
# Lấy kiểu dữ liệu của từng phần tử
types = data.apply(type)
print("Kiểu từng phần tử:")
print(types)
# Đếm
int_count = (types == int).sum()
float_count = (types == float).sum()
str_count = (types == str).sum()
print(f"\ninteger count: {int_count}")
print(f"float count: {float_count}")
print(f"string count: {str_count}")
Giải pháp 3: Dùng infer_objects / convert_dtypes (pandas hiện đại)
import pandas as pd
data = pd.Series([1, 2, "python", 3, 4, 5, 6.5])
# Chuyển đổi kiểu tối ưu
data_converted = data.convert_dtypes()
print("Dtypes sau convert_dtypes:")
print(data_converted.dtype) # string[python] hoặc object
# Với object dtype, dùng apply(type) vẫn là cách tốt nhất
type_counts = data.apply(type).value_counts()
print("\nThống kê kiểu:")
print(type_counts)
Đầu ra
integer count: 5 float count: 1 string count: 1
Lưu ý: Series pandas chỉ có 1 dtype chung. Khi chứa hỗn hợp, dtype là object. Cách đếm chính xác là kiểm tra type() từng phần tử.