【发布时间】:2018-07-23 22:20:31
【问题描述】:
我有如下所示的三列,并试图返回第三列的 top1 和 top2 最高计数。我希望生成此输出,如 expected output 所示。 数据:
打印(df)
AGE GENDER rating
0 10 M PG
1 10 M R
2 10 M R
3 4 F PG13
4 4 F PG13
代码:
s = (df.groupby(['AGE', 'GENDER'])['rating']
.apply(lambda x: x.value_counts().head(2))
.rename_axis(('a','b', 'c'))
.reset_index(level=2)['c'])
输出:
print (s)
a b
4 F PG13
10 M R
M PG
Name: c, dtype: object
预期输出:
print (s[F])
('PG13')
print(s[M])
('PG13', 'R')
【问题讨论】:
-
在输出中
PG13? -
是的,谢谢我已经编辑了
-
而
('PG13', 'R')是('PG', 'R')?
标签: python pandas pandas-groupby