首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫进阶:群后如何创建具有最大3和最小3值的多索引数据?

熊猫进阶:群后如何创建具有最大3和最小3值的多索引数据?
EN

Stack Overflow用户
提问于 2020-01-01 18:13:07
回答 2查看 166关注 0票数 0

我想知道如何创建一个多索引熊猫数据,它作为两个顶级列nlargest_3nsmallest_3,并有相应的国家和计数的每一栏。

祝贺你

日期:2020年1月1日

我的新年快乐(或者说,新的十年快乐)祝贺那位能成功回答这个问题的天才头脑。

设置

代码语言:javascript
复制
import numpy as np
import pandas as pd
np.random.seed(100)

df = pd.DataFrame({
    'country': np.random.choice(list('abcdefgh'),size=(1,1000))[0],
    'count':np.random.choice(range(10),size=(1,1000))[0]

})

print(df.head())

必填项

代码语言:javascript
复制
# this should be multi-index pandas dataframe
nlargest_3   n_smallest_3
d 140         a 112
c 135         b 116
h 128         f 120

迄今已完成

代码语言:javascript
复制
df.groupby('country')['count'].count().agg(
    [lambda ser: ser.nlargest(3),
     lambda ser: ser.nsmallest(3)]).fillna(0).pipe(print)

   <lambda>  <lambda>
d     140.0       0.0
c     135.0       0.0
h     128.0       0.0
a       0.0     112.0
b       0.0     116.0
f       0.0     120.0
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-01-01 18:25:39

这应该能起作用:

代码语言:javascript
复制
pd.merge(
    df.groupby('country')['count'].count().nlargest(3).reset_index(), 
    df.groupby('country')['count'].count().nsmallest(3).reset_index(), 
    suffixes=["_largest", "_smallest"], 
    left_index=True, right_index=True, 
    how="outer"
).set_index(["country_largest", "country_smallest"])

输出:

代码语言:javascript
复制
                                  count_largest  count_smallest
country_largest country_smallest                            
d               a                           140             112
c               b                           135             116
h               f                           128             120
票数 2
EN

Stack Overflow用户

发布于 2020-01-01 19:14:04

你的密码快到了。您只需要在Series.agg上使用函式字典,而不是使用函式清单。使用你的密码

代码语言:javascript
复制
(df.groupby('country').count()['count']
                      .agg({'nlargest': lambda x: x.nlargest(3).reset_index(), 
                            'nsmallest': lambda x: x.nsmallest(3).reset_index()}))

Out[1870]:
  nlargest       nsmallest
   country count   country count
0        d   140         a   112
1        c   135         b   116
2        h   128         f   120
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59554930

复制
相关文章

相似问题

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