我想知道如何创建一个多索引熊猫数据,它作为两个顶级列nlargest_3和nsmallest_3,并有相应的国家和计数的每一栏。
祝贺你
日期:2020年1月1日
我的新年快乐(或者说,新的十年快乐)祝贺那位能成功回答这个问题的天才头脑。
设置
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())必填项
# this should be multi-index pandas dataframe
nlargest_3 n_smallest_3
d 140 a 112
c 135 b 116
h 128 f 120迄今已完成
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发布于 2020-01-01 18:25:39
这应该能起作用:
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"])输出:
count_largest count_smallest
country_largest country_smallest
d a 140 112
c b 135 116
h f 128 120发布于 2020-01-01 19:14:04
你的密码快到了。您只需要在Series.agg上使用函式字典,而不是使用函式清单。使用你的密码
(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 120https://stackoverflow.com/questions/59554930
复制相似问题