擅长:python、mysql、java
<p>您可以使用pivot_表:<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html</a></p>
<pre><code>In [16]: df
Out[16]:
credit term Y
0 Excellent 3 safe
1 fair 5 risky
2 poor 3 risky
3 Excellent 5 safe
4 fair 5 safe
In [17]: pd.pivot_table(df, index=['credit'], columns=['Y'], aggfunc='count')
Out[17]:
term
Y risky safe
credit
Excellent NaN 2.0
fair 1.0 1.0
poor 1.0 NaN
In [18]: pd.pivot_table(df, index=['credit'], columns=['Y'], aggfunc='count', fill_value=0)
Out[18]:
term
Y risky safe
credit
Excellent 0 2
fair 1 1
poor 1 0
</code></pre>