1
$\begingroup$

I would like to find how many occurrences of a specific value count a column contains. For example, based on the data frame below, I want to find how many values in the ID column are repeated twice

| ID       | 
| -------- | 
| 000001   |            
| 000001   | 
| 000002   | 
| 000002   | 
| 000002   | 
| 000003   | 
| 000003   | 

The output should look something like this

Number of ID's repeated twice: 2
The ID's that are repeated twice are: 

| ID       | 
| -------- | 
| 000001   | 
| 000003   | 

Any help would be appreciated.

$\endgroup$

1 Answer 1

1
$\begingroup$

You can use df['var'].value_counts() to get this info. Example:

import pandas as pd
x = pd.Series(['000001',
               '000001',
               '000002',
               '000002',
               '000002',
               '000003',
               '000003'])

vc = x.value_counts()
vc.index[vc == 2]
# Index(['000003', '000001'], dtype='object')

Beware though of potential conversion of the original data into strings for the series index though. (If that is a problem, using something like df.groupby('x',as_index=False).size() may be a better option.)

$\endgroup$
2
  • $\begingroup$ The second option seemed to work perfectly fine, but it returns the column within my data frame in its entirety which can be inconvenient. Isn't there a way to filter out the specific counts of 2 and display them as a data frame itself. Furthermore, is it possible to do something like this Number of ID's repeated twice: 2 $\endgroup$
    – jibecat
    May 29 at 0:51
  • $\begingroup$ I mean you can either assign intermediate objects and work with them, or continue to do method chaining, e.g. df.groupby('x',as_index=False).size().query('size == 2').shape[0] will get you your 2, df.groupby('x',as_index=False).size().query('size == 2')['x'] will get you a series, etc. (You will need to assign the objects at some point though!) $\endgroup$
    – Andy W
    May 29 at 12:04

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.