Pandas数据框中的去重计数

3
假设我有一个名为df的Pandas DataFrame,其中包含列ab,我想要的是每个a对应的不同b值的数量。我可以执行以下操作:
distcounts = df.groupby('a')['b'].nunique()

这将得到所需的结果,但它会作为Series对象而不是另一个DataFrame对象。我想要一个DataFrame对象。在常规SQL中,我会执行以下操作:

SELECT a, COUNT(DISTINCT(b)) FROM df

我还无法完全在Pandas中模仿这个查询。该怎么办?


1
你可以在结果上调用 reset_index() 方法:distcounts = df.groupby('a')['b'].nunique().reset_index() 或者将其转换为数据框:distcounts.to_frame() - EdChum
2个回答

9

我认为你需要使用reset_index函数:

distcounts = df.groupby('a')['b'].nunique().reset_index()

示例:

df = pd.DataFrame({'a':[7,8,8],
                   'b':[4,5,6]})

print (df)
   a  b
0  7  4
1  8  5
2  8  6

distcounts = df.groupby('a')['b'].nunique().reset_index()
print (distcounts)
   a  b
0  7  1
1  8  2

3

另一种选择是使用Groupby.agg

df.groupby('a', as_index=False).agg({'b': 'nunique'})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接