如何根据其中的值数量删除 pandas 列?

How to drop a pandas column based on number of values in it?

事实证明,在尝试删除包含分类数据(0 和 1)的列时,我无法获得所需的结果。我尝试了几个程序,但它们都产生了相同的结果:数据框本身包含所有列。

df1.drop([i for i in df1 if df1[i].nunique == 2], axis = 1, inplace = True)

这是我尝试过的一种方式。还有一个如下:

df1.drop(df.columns[df.apply(lambda col: col.nunique == 2)], axis = 1)

有人可以帮忙吗?谢谢

一种方法是获取所有布尔值的列,然后如下所示删除,如果列中的数据类型被正确分类,这将起作用。选择适当地传递数据类型 .dtypes

bool_col = []
for cols in df:
    if df[col].dtypes == "bool":
        non_floats.append(col)
df = df.drop(columns=non_floats)

你的第一次尝试很完美。你只需要将 () 添加到 df1[i].nunique 就可以变成这样: df1.drop([i for i in df1 if df1[i].nunique() == 2], axis = 1, inplace = True)