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
: