This question already has an answer here:
- Pandas count(distinct) equivalent 5 answers
original title: "python - Count unique values with pandas per groups"
This question already has an answer here:
इस सवाल का पहले से ही एक जवाब है यहाँ: पंडों की गिनती (अलग) समकक्ष 5 उत्तर ...
यह अनुवाद के बाद का सारांश है, अगर आपको पूरा अनुवाद देखने की आवश्यकता है, तो कृपया 'अनुवाद' आइकन पर क्लिक करें
You need
nunique
:If you need to
strip
'
characters:Or as Jon Clements commented:
You can retain the column name like this:
The difference is that
nunique()
returns a Series andagg()
returns a DataFrame.Generally to count distinct values in single column, you can use
Series.value_counts
:To see how many unique values in a column, use
Series.nunique
:To get all these distinct values, you can use
unique
ordrop_duplicates
, the slight difference between the two functions is thatunique
return anumpy.array
whiledrop_duplicates
returns apandas.Series
:As for this specific problem, since you'd like to count distinct value with respect to another variable, besides
groupby
method provided by other answers here, you can also simply drop duplicates firstly and then dovalue_counts()
:df.domain.value_counts()
IIUC you want the number of different
ID
for everydomain
, then you can try this:output:
You could also use
value_counts
, which is slightly less efficient.But the best is Jezrael's answer usingnunique
: