<p>您需要<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer">^{<cd1>}</a>by <code>MultiIndex</code>by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer">^{<cd4>}</a>的第一级唯一值的所有组合:</p>
<pre><code>s = (df.groupby(['Environment/s Affected',
(df['Rating'].isin(['1', '2']))]).size()
.rename(index={True: 'Critical', False: 'Others P3+'}, level=1))
print (s)
Environment/s Affected Rating
Env1 Others P3+ 6
Env2 Others P3+ 4
Env3 Others P3+ 6
Env4 Others P3+ 7
Test5 Others P3+ 7
dtype: int64
mux = pd.MultiIndex.from_product([df['Environment/s Affected'].unique(),
['Others P3+', 'Critical']],
names=['Environment/s Affected','Rating'])
print (mux)
MultiIndex(levels=[['Env1', 'Env2', 'Env3', 'Env4', 'Test5'], ['Critical', 'Others P3+']],
codes=[[0, 0, 1, 1, 2, 2, 3, 3, 4, 4], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]],
names=['Environment/s Affected', 'Rating'])
df1 = s.reindex(mux, fill_value=0).reset_index(name='counts')
print (df1)
Environment/s Affected Rating counts
0 Env1 Others P3+ 6
1 Env1 Critical 0
2 Env2 Others P3+ 4
3 Env2 Critical 0
4 Env3 Others P3+ 6
5 Env3 Critical 0
6 Env4 Others P3+ 7
7 Env4 Critical 0
8 Test5 Others P3+ 7
9 Test5 Critical 0
</code></pre>
<p>如果需要<code>Critical</code>在最后一行添加<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer">^{<cd6>}</a>:</p>
^{pr2}$