python - pandas.DataFrame.groupby.nunique() 不会删除 groupby 列。这是一个错误吗?

标签 python pandas pandas-groupby

虽然我将参数 as_index 设置为 True,但 pandas.DataFrame.groupby.nunique() 会保留我在结果中分组的列。

pandas版本是:0.24.1

df = pd.DataFrame(
    {'a': [1, 1, 2, 3, 2],
     'b': [1, 2, 3, 4, 4]}
)
df.groupby('a', as_index=True).nunique()

输出为:

#    a  b
# a      
# 1  1  2
# 2  1  2
# 3  1  1

我预计:

#    b
# a   
# 1  2
# 2  2
# 3  1

作为一个行为符合预期的反例:

df.groupby('a', as_index=True).max()

结果:

#    b
# a   
# 1  2
# 2  4
# 3  4

最佳答案

如果你运行[print(df.to_string() + '\n') for i, df in df.groupby('a', as_index=True)],你会得到打印:

   a  b
0  1  1
1  1  2

   a  b
2  2  3
4  2  4

   a  b
3  3  4

a 列未设置为每个数据框组的索引。它是 groupby 的输出,当 as_index=True(这也是默认值)时,其索引设置为组索引,而不是数据帧组本身。

关于python - pandas.DataFrame.groupby.nunique() 不会删除 groupby 列。这是一个错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57590796/

相关文章:

Python vlc 安装问题

python - 返回生成器的函数名称

python - Pandas - 根据多个 `or` 条件删除行

python - 如何将assertSequenceEqual与pandas系列一起使用?

python - 是否有一种快速的方法来填充间隙(可能是多个)之间的 NA 值,并且仅当间隙小于一定大小时?

python - 如何分组然后将结果写入 csv(以及更多)

Python BZ2 IOError : invalid data stream

python - 我可以将图像列表传递给ffmpeg-python的输入法吗

python - 查询hdf5日期时间列

python-3.x - 使用groupby后如何从Pandas数据框中选择行?