简体   繁体   中英

Count distinct values for each column, return a dataframe, and sort values

This is my code:

for column in list(data.columns):
    pd.DataFrame(columns=column, data=data.columns.nunique()).sort_values()

This doesn't work......

Either to define a function or use a for loop, how can I make it simple to check the unique value number of each column?

There are many issues with your code, but the two main ones:

  • You don't store, print, or append to a list the pd.DataFrame objects you create.
  • You are applying nunique to column labels, not to the data within your dataframe.

Here you can use nunique directly with your dataframe, then sort_values :

np.random.seed(0)
df = pd.DataFrame(np.random.randint(0, 10, (5, 5)))

res = df.nunique()\
        .sort_values(ascending=False)\
        .rename('Count')\
        .to_frame()

print(res)

   Count
1      5
3      4
2      4
0      4
4      3

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