我有一張這樣的表:
import pandas as pd
df = pd.DataFrame(
[
['john', 'rdgsdr', 2, 'A'],
['ann', 'dsdfds', 3, 'A'],
['john', 'jkfgdj', 1, 'B'],
['bob', 'xcxfcd', 5, 'A'],
['john', 'uityuu', 3, 'C'],
['ann', 'werwwe', 2, 'C'],
],
columns=['name', 'stuff', 'orders', 'store']
)
# df
# name stuff orders store
# 0 john rdgsdr 2 A
# 1 ann dsdfds 3 A
# 2 john jkfgdj 1 B
# 3 bob xcxfcd 5 A
# 4 john uityuu 3 C
# 5 ann werwwe 2 C
我需要為每個名稱提取具有最大訂單數的行;并為該名稱計算所有商店的串列。像這樣:
grouped = df.groupby('name')
for name, group in grouped:
print('-'*5, name, '-'*5)
print(group)
# ----- ann -----
# name stuff orders store
# 1 ann dsdfds 3 A <- max(orders) for ann
# 5 ann werwwe 2 C
# ----- bob -----
# name stuff orders store
# 3 bob xcxfcd 5 A <- max(orders) for bob
# ----- john -----
# name stuff orders store
# 0 john rdgsdr 2 A
# 2 john jkfgdj 1 B
# 4 john uityuu 3 C <- max(orders) for john
# ##########################
# This is what I want to get
# ##########################
>>> result
name stuff max orders all stores
1 ann dsdfds 3 A,C
3 bob xcxfcd 5 A
4 john uityuu 3 A,B,C
我試過這個:
result = grouped.agg(
**{
# 'stuff': 'stuff',
'max orders': pd.NamedAgg('orders', max),
'all stores': pd.NamedAgg('store', lambda s: s.str.join(',')),
}
)
但我不知道如何在結果中包含“東西”列(在我的真實應用程式中,我有很多這樣的附加列,可能有幾十個)。而且,連接給了我串列而不是字串:
>>> result
name max orders all stores
0 ann 3 [A, C]
1 bob 5 A
2 john 3 [A, B, C]
uj5u.com熱心網友回復:
試試 first
out = df.set_index('stuff').groupby('name').agg(stuff = ('orders' , 'idxmax'),
max_orders = ('orders' , 'max'),
all_stores = ('store',','.join))#.reset_index()
Out[200]:
stuff max_orders all_stores
name
ann dsdfds 3 A,C
bob xcxfcd 5 A
john uityuu 3 A,B,C
uj5u.com熱心網友回復:
您可以通過將此答案與 groupby結合以獲取他們曾作業過的商店串列來做到這一點。
# Get stores that each person works at
stores_for_each_name = df.groupby('name')['store'].apply(','.join)
# Get row with largest order value for each name
df = df.sort_values('orders', ascending=False).drop_duplicates('name').rename({'orders': 'max_orders'}, axis=1)
# Replace store column with comma-separated list of stores they have worked at
df = df.drop('store', axis=1)
df = df.join(stores_for_each_name, on='name')
輸出:
name stuff max_orders store
3 bob xcxfcd 5 A
1 ann dsdfds 3 A,C
4 john uityuu 3 A,B,C
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/376792.html
下一篇:使用Python回傳鍵嵌套字典
