Python 如何识别所有列中具有20个以上唯一值的列

Python 如何识别所有列中具有20个以上唯一值的列,python,pandas,Python,Pandas,对于pandas_python中的所有列,只需要分隔具有20个以上唯一值的列(这是一个解决方案):如果还有更好的方法,请评论: enter code here col_with_morethan_20_unique_values_cat=[] for col in data.columns: if data[col].dtype =='O': if len(data[col].unique()) >20: col_with_morethan_

对于pandas_python中的所有列,只需要分隔具有20个以上唯一值的列(这是一个解决方案):如果还有更好的方法,请评论:

enter code here
col_with_morethan_20_unique_values_cat=[]
for col in data.columns:
    if data[col].dtype =='O':
        if len(data[col].unique()) >20:
            col_with_morethan_20_unique_values_cat.append(data[col].name)
        else:
            continue

print(col_with_morethan_20_unique_values_cat)
print('total number of columns with more than 20 number of unique value is',len(col_with_morethan_20_unique_values_cat))



 # The o/p will be as:
['CONTRACT NO', 'X2','X3',,,,,,,..]
total number of columns with more than 20 number of unique value is 25

现在,通过理解列表并给出两个条件,可以获得相同的结果 1). 如果列的数据类型为“O”-对象/类别 2). 而且如果唯一值大于任何计数(这里是20)。 获得了与前一个类似的结果

cols_more_than_20 = [col for col in data.columns if data[col].dtype =='O' and data[col].nunique()  > 20]

感谢@nag的响应,现在我在if语句中又添加了一个条件,以获得我以前代码的精确副本结果。即,编辑代码以检查用于检查列的数据类型的条件,并且仅当它是分类的(非数字)时才允许继续
cols_more_than_20 = [col for col in data.columns if data[col].dtype =='O' and data[col].nunique()  > 20]