我的df:
Test_Data = [('Client', ['A', 'A', 'A', 'B', 'B', 'B','C','C']),
('Currency', ['USD', 'EUR', 'USD', 'AUD', 'EUR', 'USD', 'GBP', 'USD']),
('SalesPerson', ['Dave', 'Dave', 'Bob', 'Dave', 'Dave', 'Bob','Dave','Bob']),
('Done_Trades', [1,1,2,3,3,4,5,6]),
('Average_Qty', [10, 50, 100, 10, 50, 1000, 50, 100]),
('Average_Qty_CAD', [1, 2, 3, 30,20, 10,1,2])
df = pd.DataFrame(dict(Test_Data))
print(df)
Client Currency SalesPerson Done_Trades Average_Qty Average_Qty_CAD
0 A USD Dave 1 10 1
1 A EUR Dave 1 50 2
2 A USD Bob 2 100 3
3 B AUD Dave 3 10 30
4 B EUR Dave 3 50 20
5 B USD Bob 4 1000 10
6 C GBP Dave 5 50 1
7 C USD Bob 6 100 2
a。客户B的每个客户的平均值_数量_CAD总和最高(60),因此首先显示它,然后是A(6),然后是C(3)。
b。在B中,Dave具有最高的Average_Qty_CAD(30),然后是第二(20),而Bob具有第三(10),因此我们希望B的行排序为30,20,10。
c。在A中,Bob具有最高的Average_Qty_CAD(3),然后是Dave的两个条目(2,1),因此我们希望A有序3,2,1。
d。在C中,鲍勃的最高Average_Qty_CAD(1002,然后是戴夫(1),因此,阶数2、1如果我想让每个客户的总和显示Average_Qty_CAD,需要添加什么?
所需的df:
Client Currency SalesPerson Done_Trades Average_Qty Average_Qty_CAD Total per Client
2 B AUD Dave 3 10 30 60
1 B EUR Dave 3 50 20 60
0 B USD Bob 4 1000 10 60
3 A USD Bob 2 100 3 6
4 A EUR Dave 1 50 2 6
5 A USD Dave 1 10 1 6
6 C USD Bob 6 100 2 3
7 C GBP Dave 5 50 1 3
答案 0 :(得分:2)
IIUC,您可以执行以下操作:
doFinal()
m=(df.reindex(df.groupby('Client').Qty_CAD.transform(sum).
sort_values(ascending=False).index).reset_index(drop=True))
print(m)
答案 1 :(得分:1)
先将GroupBy.transform
与sum
和DataFrame.sort_values
一起使用:
df['Total per Client'] = df.groupby('Client')["Average_Qty_CAD"].transform('sum')
df = (df.sort_values(by=["Total per Client", "Client", "Average_Qty_CAD"],
ascending=[False, True, False]))
print (df)
Client Currency SalesPerson Done_Trades Average_Qty Average_Qty_CAD \
3 B AUD Dave 3 10 30
4 B EUR Dave 3 50 20
5 B USD Bob 4 1000 10
2 A USD Bob 2 100 3
1 A EUR Dave 1 50 2
0 A USD Dave 1 10 1
7 C USD Bob 6 100 2
6 C GBP Dave 5 50 1
Total per Client
3 60
4 60
5 60
2 6
1 6
0 6
7 3
6 3
答案 2 :(得分:0)
这可以完成工作,而不是我想要的那么优雅:
# Get Totals per client
aux = df.groupby('Client')["Average_Qty_CAD"].sum().rename("Total per Client").reset_index()
print(aux)
# Merge Totals per client with original df and sort
# In case of tie, you want to sort by ascending client
m = df.merge(aux).sort_values(by=["Total per Client", "Client", "Average_Qty_CAD"], ascending=[False, True, False])
print(m)