我有一張產品表及其以美元計的銷售額。我有總銷量,想知道哪些產品占總銷量的 80%,并在標簽欄中標記為 1。請確保從最大數字到最小數字標記 1。低于總賣出量為 32,其中 80% 為 25.6。因此,如果我們添加第 2、4、5 和 7 行,從 sell$ 列中的最大數字到最小數字,它將是 26,這使得總銷量的 80% 為 32,并將它們標記為 1,其他標記為 0。我想用python和pandas來做。先感謝您。此致

uj5u.com熱心網友回復:
計算每個產品的銷售額比例,按比例排序,計算它們的累計總和,然后使用它來獲得前 80%
cumsum = (df["sold"]/df["sold"].sum()).sort_values().cumsum()
df["label"] = pd.Series(0, index=cumsum.index).where(cumsum <= 0.2, 1)
uj5u.com熱心網友回復:
你可以這樣做:
import pandas as pd
import numpy as np
data = {'productID':[1,2,3,4,5,6,7],'sold$':[2,4,3,8,5,1,9]}
df=pd.DataFrame(data)
df.sort_values('sold$',inplace=True)
df['Label']=np.where(df['sold$'].cumsum()<=df['sold$'].sum() * 0.2,0,1)
df.sort_index(inplace=True)
print (df)
結果:
productID sold$ Label
0 1 2 0
1 2 4 1
2 3 3 0
3 4 8 1
4 5 5 1
5 6 1 0
6 7 9 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/333432.html
上一篇:如何使用Pandas遍歷列?
下一篇:選擇與字串包含完全匹配的行
