遍历 DataFrame 列名列表,仅将值为整数或浮点数的列名添加到新列表

Iterate through a list of DataFrame column names and add only the column names whose values are integers or floats to a new list

这是数据帧的快照:

这是我尝试使用的代码 运行:

第一个列表包含具有 empty/NaN 个值的所有条目的列名

cols_missing_values = [col for col in X1_train.columns if X1_train[col].isnull().any()]

下面是我尝试使用列表理解来创建一个新列表,该列表仅包含数据类型为整数或浮点数的列名。

cols_missing_values_numbers = [col for col in cols_missing_values if X1_train.dtypes is type == int or float] cols_missing_values_numbers

这是我当前得到的错误:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

总的来说,我要做的是在 DataFrame 中找到我可以使用插补的列名。我打算删除具有空值或缺失值但包含分类数据的列。

df = pd.DataFrame(
    {'int_col': [1, 2, 3], 
     'float_col': [1.1, 2.2, 3.3], 
     'obj_col': list('abc')})

>>> [col for col in df if df[col].dtype in [np.dtype(t) for t in ('int', 'float')]]
['int_col', 'float_col']

要在列上添加空条件:

cols_missing_values_numbers = [
    col for col in df 
    if df[col].dtype in [np.dtype(t) for t in ('int', 'float')] 
    and df[col].isnull().any()
]