简体   繁体   中英

Use python def function to append for a list

There're a few categorical features in my dataset. I want to know how many unique numbers of each categorical feature coz I won't convert those with large unique numbers.

Instead of using df['column name'].nunique() to each feature one at a time, I want to get all numbers at once. Below, I'm trying to make a list of unique numbers per categorical column by defining a function but only get an empty list as result. I hope someone can figure out why my code doesn't work.

 #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

Instead of creating list of all categorical and then using for loop and appending number of unique value to a new list

Just use this:-

n_unique=hotel.nunique().to_list()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM