使用
groupby
value_counts
:
df.groupby(['name', 'day']).location.value_counts(normalize=True).mul(100)
name day location
Alice friday left 50.0
right 50.0
Bob monday left 100.0
Name: location, dtype: float64
对您想要的输出进行更多的清洁:
out = (df.groupby(['name', 'day']).location.value_counts(normalize=True).mul(100)
.rename('row_percent').reset_index(2))
location row_percent
name day
Alice friday left 50.0
friday right 50.0
Bob monday left 100.0
out == expected
location row_percent
name day
Alice friday True True
friday True True
Bob monday True True