如何在Pandas中排除float64、float32、float16所有浮点类型列?
解决pandas select_dtypes无法识别float16/32的问题
你可以通过两种方式实现排除所有浮点类型列:
显式列出所有浮点类型:
使用exclude=[np.float16, np.float32, np.float64],把所有需要排除的浮点类型逐一指定,适合需要精准控制的场景。更简洁的通用方式:利用numpy浮点父类
所有numpy浮点类型都是np.floating的子类,直接写exclude=[np.floating]就能一次性匹配float16、float32、float64,代码更简洁且覆盖所有浮点类型。
举个实际验证的例子:
import pandas as pd import numpy as np # 创建包含多种浮点类型的测试DataFrame df = pd.DataFrame({ 'float16_col': pd.Series([1.1, 2.2], dtype=np.float16), 'float32_col': pd.Series([3.3, 4.4], dtype=np.float32), 'float64_col': pd.Series([5.5, 6.6], dtype=np.float64), 'int_col': [1, 2], 'str_col': ['x', 'y'] }) # 排除所有浮点类型列 filtered_df = df.select_dtypes(exclude=[np.floating]) print(filtered_df.dtypes)
运行后会发现,所有浮点类型的列都被排除,仅保留整数和字符串类型的列。
之前用exclude=["float"]无效的原因是:pandas里的字符串"float"仅对应np.float64类型,无法匹配float16和float32这类其他浮点类型。
内容的提问来源于stack exchange,提问作者TRK
相关产品推荐
相关产品推荐

