Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas - number of unique rows occurrences in dataframe

Tags:

python

pandas

How can I count number of occurrences of each unique row in a DataFrame?

df = {'x1': ['A','B','A','A','B','A','A','A'], 'x2': [1,3,2,2,3,1,2,3]}
df = pd.DataFrame(df)

df
  x1  x2
0  A   1
1  B   3
2  A   2
3  A   2
4  B   3
5  A   1
6  A   2
7  A   3

And I would like to obtain

   x1  x2 count 
0   A   1     2
1   A   2     3
2   A   3     1
3   B   3     2
like image 420
Pepacz Avatar asked Nov 11 '16 15:11

Pepacz


People also ask

How do you count how many unique rows a DataFrame has?

Count Unique Rows in Pandas DataFrameUsing nunique() method, we can count unique rows in pandas. by default nunique() shows axis=0 that means rows but it can be changed to axis=1.

How do you count unique occurrences in pandas?

You can use the nunique() function to count the number of unique values in a pandas DataFrame.


1 Answers

You could also drop duplicated rows:

In [4]: df.shape[0]
Out[4]: 8

In [5]: df.drop_duplicates().shape[0]
Out[5]: 4
like image 173
Vlados Avatar answered Oct 07 '22 23:10

Vlados