【发布时间】:2021-11-16 23:16:13
【问题描述】:
假设我有一个这样的数据框:
import pandas as pd
df = pd.DataFrame([
('a', 'aa'),
('b', 'aa'),
('c', 'bb'),
('d', 'bb'),
('e', 'cc'),
('f', 'cc'),
('h', 'cc')
], columns=['group', 'id'])
我做了一个 groupby 来显示唯一值的计数以及唯一值本身。这是我现在正在做的事情:
df1 = df.groupby(["id"])["group"].nunique()
print(df1)
id
aa 2
bb 2
cc 3
df2 = df.groupby(['id'])['group'].agg(['unique'])
print(df2)
id
aa [a, b]
bb [c, d]
cc [e, f, h]
但是,我试图让这两个显示在彼此旁边(一列显示计数,一列显示值,如下所示。有什么办法吗?
id count values
aa 2 [a, b]
bb 2 [c, d]
cc 3 [e, f, h]
【问题讨论】:
标签: python pandas pandas-groupby