这会很有用所以我知道有多少个我必须执行计算的唯一组。谢谢。
假设groupby对象被称为dfgroup
。
答案 0 :(得分:40)
作为documented,您可以获得len(dfgroup)
组的数量。
答案 1 :(得分:15)
从v0.23开始,有多个选项可供使用。首先,设置,
df = pd.DataFrame({'A': list('aabbcccd'), 'B': 'x'})
df
A B
0 a x
1 a x
2 b x
3 b x
4 c x
5 c x
6 c x
7 d x
g = df.groupby(['A'])
ngroups
较新版本的groupby API提供了此(未记录的)属性,该属性存储GroupBy对象中的组数。
g.ngroups
# 6
请注意,这与实际返回组本身的GroupBy.groups
不同:
g.groups
# {'a': Int64Index([0, 1], dtype='int64'),
# 'b': Int64Index([2, 3], dtype='int64'),
# 'c': Int64Index([4, 5, 6], dtype='int64'),
# 'd': Int64Index([7], dtype='int64')}
len
如BrenBarn's answer所示,您可以直接在len
对象或GroupBy
属性(如上所示)上调用GroupBy.groups
。
len(g)
# 6
len(g.groups)
# 6
这已在GroupBy
object attributes中记录。
为了完整性,您还可以迭代groupby对象,明确计算每个组:
sum(1 for _ in g)
# 6
你很幸运。我们有一个函数,GroupBy.size
。
g.size()
A
a 2
b 2
c 3
d 1
dtype: int64
请注意,size
也会计算NaN。如果您不想计算NaN,请改用GroupBy.count
。
答案 2 :(得分:-1)
您可以将格式说明符用作:
"73E5-16AC-260C-3C8C"
,您将文件名另存为: filename_1.csv