擅长:python、mysql、java
<p>要按多个条件分组,请传递列或条件的列表:</p>
<pre><code>df['birthdate'].groupby([df.birthdate.dt.year, df.birthdate.dt.month]).agg('count')
</code></pre>
<p>示例:</p>
<pre><code>In [165]:
df = pd.DataFrame({'birthdate':pd.date_range(start=dt.datetime(2015,12,20),end=dt.datetime(2016,3,1))})
df.groupby([df['birthdate'].dt.year, df['birthdate'].dt.month]).agg({'count'})
Out[165]:
birthdate
count
birthdate birthdate
2015 12 12
2016 1 31
2 29
3 1
</code></pre>
<p><strong>更新</strong></p>
<p>从版本<a href="https://github.com/pandas-dev/pandas/issues/21075" rel="noreferrer">^{<cd1>}</a>开始,由于多索引级别名称必须唯一的限制,上述代码不再工作,现在需要<code>rename</code>级别才能工作:</p>
<pre><code>In[107]:
df.groupby([df['birthdate'].dt.year.rename('year'), df['birthdate'].dt.month.rename('month')]).agg({'count'})
Out[107]:
birthdate
count
year month
2015 12 12
2016 1 31
2 29
3 1
</code></pre>