<p>我可以用组计数成功地填充我的新列,但我怀疑有一种更简单的方法:</p>
<pre><code># How do I simplify this?
def f(gr):
return pd.Series([gr['class_name'].count()] * gr.shape[0], index=gr.index)
df['class_size'] = df.groupby("class_name").apply(f).reset_index(level=0, drop=True)
column_list = ['class_name', 'class_size']
df[column_list].head(5)
</code></pre>
<p>获取:</p>
<p><a href="https://i.stack.imgur.com/ViTYE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ViTYE.png" alt="This is just the first few rows of data - see how the same class name has the same class count?"/></a></p>