擅长:python、mysql、java
<p>您可以使用<code>groupby</code>:</p>
<pre><code>In [2]: df = pd.DataFrame({'company': ['ford', 'chevy', 'ford', 'ford', 'ford', 'toyota'],
'model': ['mustang', 'camaro', 'fiesta', 'focus', 'taurus', 'camry'],
'rating': ['A', 'B', 'C', 'A', 'B', 'B'],
'type': ['coupe', 'coupe', 'sedan', 'sedan', 'sedan', 'sedan']})
In [3]: df.groupby('rating').count()['model'] / len(df)
Out[3]:
rating
A 0.333333
B 0.500000
C 0.166667
Name: model, dtype: float64
In [4]: (df.groupby(['rating', 'type']).count() / df.groupby('rating').count())['model']
Out[4]:
rating type
A coupe 0.500000
sedan 0.500000
B coupe 0.333333
sedan 0.666667
C sedan 1.000000
Name: model, dtype: float64
</code></pre>