如何根据条件获取列的百分比? Python

How to get the Percentage of a Column based on a Condition? Python

我想根据每个相关国家/地区的出现次数来计算我的产品列的百分比。非常感谢您的帮助。

这是我到目前为止所做的, 我用这段代码计算了我的新数据框:

gb = data1.groupby(['Country', 'Products']).size()
df = gb.to_frame(name = 'ProductsCount').reset_index()
df

这给了我看起来像这样的东西:

   Countries    Products     ProductsCount
0  Country 1     Product 1     5
1  Country 1     Product 2     31
2  Country 2     Product 1     2
3  Country 2     Product 2     1

注意:我有几千行输出。

我的目标是直接根据国家/地区获取每种产品的百分比,而不计算 ['ProductsCount'],如下所示:

   Countries    Products     Percentage
0  Country 1     Product 1     0.138
1  Country 1     Product 2     0.861
2  Country 2     Product 1     0.667
3  Country 2     Product 2     0.333

否则如果我不能让输出只显示 %,那么我想要这样的东西:

   Countries    Products     ProductsCount   Products%
0  Country 1     Product 1     5                0.138
1  Country 1     Product 2     31               0.861
2  Country 2     Product 1     2                0.667
3  Country 2     Product 2     1                0.333

我使用以下代码设法根据整个数据集仅计算了百分比:

df['Products%'] = df.ProductsCount/len(df.Country)

提前致谢!

使用 SeriesGroupBy.value_countsnormalize=True 参数:

df = (data1.groupby('Countries')['Products']
           .value_counts(normalize=True,sort=False)
           .reset_index(name='Percentage'))
print (df)
   Countries   Products  Percentage
0  Country 1  Product 1    0.138889
1  Country 1  Product 2    0.861111
2  Country 2  Product 1    0.666667
3  Country 2  Product 2    0.333333

编辑:

df = (data1.groupby('Countries')['Products']
           .value_counts(sort=False)
           .reset_index(name='ProductsCount')
           .assign(Percentage = lambda x: x['ProductsCount'].div(len(x))))
print (df)