簡體   English   中英

如何根據條件獲取列的百分比? 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM