<p>你需要<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="noreferrer">^{<cd1>}</a>:</p>
<pre><code>df = df.groupby('domain')['ID'].nunique()
print (df)
domain
'facebook.com' 1
'google.com' 1
'twitter.com' 2
'vk.com' 3
Name: ID, dtype: int64
</code></pre>
<p>如果需要<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="noreferrer">^{<cd2>}</a><code>'</code>字符:</p>
<pre><code>df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com 1
google.com 1
twitter.com 2
vk.com 3
Name: ID, dtype: int64
</code></pre>
<p>或按<a href="https://stackoverflow.com/questions/38309729/count-unique-values-with-pandas#comment64036411_38309823">Jon Clements</a>注释:</p>
<pre><code>df.groupby(df.domain.str.strip("'"))['ID'].nunique()
</code></pre>
<p>您可以这样保留列名:</p>
<pre><code>df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
domain ID
0 fb 1
1 ggl 1
2 twitter 2
3 vk 3
</code></pre>
<p>区别在于<code>nunique()</code>返回一个序列,而<code>agg()</code>返回一个数据帧。</p>