I have a dataframe with date and cat_1 variables among other variables. I want to get number of unique values of cat_1, per date. Here is an example: Below is a toy dataframe.

         date foo
0  2019-04-21   a
1  2019-04-21   b
2  2019-04-23   c
3  2019-05-01   c
4  2019-05-01   c
5  2019-04-23   a

I want to get is the following:

2019-04-21    2
2019-04-23    2
2019-05-01    1

I got it, but I think it is a bit convoluted. My code:


Is there any other straightforward way to get the same answer?



Try nunique(). That should do it. Here is a toy example:

import pandas as pd

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                          'foo', 'bar', 'foo', 'foo'],
                   'B' : ['one', 'one', 'two', 'three',
                          'two', 'two', 'one', 'two']})



     A      B
0  foo    one
1  bar    one
2  foo    two
3  bar  three
4  foo    two
5  bar    two
6  foo    one
7  foo    two



then gives

bar    3
foo    2
Name: B, dtype: int64

For more details check this question on SO.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.