擅长:python、mysql、java
<p>对于缺少对的add<code>0</code>值,需要添加<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="nofollow noreferrer">^{<cd1>}</a>:</p>
<pre><code>mux = pd.MultiIndex.from_product([df['rating'].unique(), df['type'].unique()])
s = (df.groupby(['rating', 'type']).count() / df.groupby('rating').count())['model']
s = s.reindex(mux, fill_value=0)
print (s)
A coupe 0.500000
sedan 0.500000
B coupe 0.333333
sedan 0.666667
C coupe 0.000000
sedan 1.000000
Name: model, dtype: float64
</code></pre>
<p>还有另一个解决方案,谢谢<a href="https://stackoverflow.com/questions/37818063/how-to-calculate-conditional-probability-of-values-in-dataframe-pandas-python/46515289?noredirect=1#comment79984746_46515289">Zero</a>:</p>
<pre><code>s.unstack(fill_value=0).stack()
</code></pre>