首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Groupby,transpose和前5名

Groupby,transpose和前5名
EN

Stack Overflow用户
提问于 2022-04-25 18:44:54
回答 2查看 48关注 0票数 0

我有这样的数据:

代码语言:javascript
复制
d = {'col1': ['Category1', 'Category1','Category1', 'Category1','Category1', 'Category2','Category2', 'Category2','Category2', 'Category2',], 
 'col2': ['Type1', 'Type2','Type3','Type4','Type5','Type1', 'Type2','Type3','Type4','Type5'], 
 'col3':[32,44,87,10,12,10,14,800,3200,35]}

df_test = pd.DataFrame(data=d)

df_test

col1        col2    col3
Category1   Type1   32
Category1   Type2   44
Category1   Type3   87
Category1   Type4   10
Category1   Type5   12
Category2   Type1   10
Category2   Type2   14
Category2   Type3   800
Category2   Type4   3200
Category2   Type5   35

我想要得到的是两行,类别1和类别2,包含基于col3编号的排序的3最大类型。所以输出将如下所示:

代码语言:javascript
复制
col1       order1  order2  order3
Category1  Type3   Type2   Type1
Category2  Type4   Type3   Type5

我试过:

代码语言:javascript
复制
df_test=df_test.groupby(['col1']).apply(lambda x: (x.groupby('col2')
                                      .sum()
                                      .sort_values('col3', ascending=False))
                                      .head(3)).T

和其他不同的方式都没有成功。有什么想法吗?谢谢

EN

回答 2

Stack Overflow用户

发布于 2022-04-25 19:04:28

代码语言:javascript
复制
df_test['col3'] = df_test.groupby('col1')['col3'].rank(ascending = False)
df1 = df_test.query('col3 <= 3').reset_index(drop = True)
df1['col4'] = 'order' + df1['col3'].astype(int).astype(str)
df1.pivot('col1', 'col4', 'col2').reset_index()

col3       col1 order1 order2 order3
0     Category1  Type3  Type2  Type1
1     Category2  Type4  Type3  Type5
票数 0
EN

Stack Overflow用户

发布于 2022-04-25 19:51:28

代码语言:javascript
复制
df_t = df.pivot(columns='col2', index='col1')
df_t = df_t.apply(lambda s: [x[1] for x in s.nlargest(3).index], axis=1)
print(df_t)

输出:

代码语言:javascript
复制
col1
Category1    [Type3, Type2, Type1]
Category2    [Type4, Type3, Type5]
dtype: object
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72004314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档