使用 python def 函数追加列表

Use python def function to append for a list

我的数据集中有一些分类特征。我想知道每个分类特征有多少个唯一数字,因为我不会转换那些具有大唯一数字的特征。

我不想一次对每个特征使用 df['column name'].nunique(),而是想一次获取所有数字。下面,我试图通过定义一个函数来为每个分类列制作一个唯一数字列表,但结果只得到一个空列表。我希望有人能弄清楚为什么我的代码不起作用。

 #make a list of all categorical features
 
 cat_feats=['hotel','arrival_date_month','assigned_room_type','customer_type','deposit_type','distribution_channel','market_segment','meal','reserved_room_type',
 'country','reservation_status','reservation_status_date']
 

# define a function
 n_unique = [] 
def function(cat_feats):
    for x in cat_feats:
        n = hotel['x'].nunique()
        n_unique.append(n)
    return n_unique

而不是创建所有分类的 list 然后使用 for loop 并将唯一值的数量附加到新的 list

就用这个:-

n_unique=hotel.nunique().to_list()