0

How to count a number of unique values in multiple columns in Python, pandas etc. I can do for one column using "nunique" function. I need something like:

print("Number of unique values in Var1", DF.var1.nunique(),sep="= ").

For all the variables in the dataset. Something like a loop or apply function maybe. I tried a lot of things failed to get what I desired.

Thanks for the help!

6
  • If you tried things, show us what you tried. :) Commented Jan 8, 2018 at 15:21
  • 1
    Use apply like df.apply(pd.Series.nunique) Commented Jan 8, 2018 at 15:27
  • 1
    @Dark, a bit simplified version: df.agg('nunique') Commented Jan 8, 2018 at 15:28
  • 2
    @Maxu we might be overthinking its just df.nunique() Commented Jan 8, 2018 at 15:30
  • @Dark, yeah, I didn't notice - it was added in Pandas 0.20.0 Commented Jan 8, 2018 at 15:31

1 Answer 1

5

You want to print number of unique values per column, so use:

for k, v in df.nunique().to_dict().items():
    print('{}={}'.format(k,v))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.