虽然我将参数 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/