熊猫:groupby对象是否存储索引?

时间:2019-05-25 15:35:57

标签: python pandas

据我了解,groupby需要计算分组变量的索引。但是,我不确定这是否存储在groupby对象中。

我的代码看起来像

df.groupby(["col1","col2"]).agg( something )
( ... some code ... )
df.groupby(["col1","col2"]).agg( something else )

我是否正确理解以下内容将避免两次建立索引?

my_group = groupby(["col1","col2"])
my_group.agg( something )
( ... some code ... )
my_group.agg( something else )

这对我很重要,因为我写的东西必须两次通过组,并且如果未存储索引,则可能必须实现自己的groupby

1 个答案:

答案 0 :(得分:1)

是,groupby计算索引以计算聚合,如果可以将其存储在groupby对象中,它将再次存储正在构建的索引

df3 = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar"],
                    "B": ["one", "one", "one", "two", "two",
                          "one", "one", "two", "two"],
                    "C": ["small", "large", "large", "small",
                          "small", "large", "small", "small",
                         "large"],
                    "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                    "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
df4 = df3.sort_values(['A','B'])
res1 = df3.groupby(['A', 'B'])['D'].mean()
res2 = df4.groupby(['A', 'B'])['D'].median()

print res1.index
MultiIndex(levels=[[u'bar', u'foo'], [u'one', u'two']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=[u'A', u'B'])

print res2.index
MultiIndex(levels=[[u'bar', u'foo'], [u'one', u'two']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=[u'A', u'B'])

您绝对可以做到

my_group = df3.groupby(['A', 'B']) 
print type(my_group)
pandas.core.groupby.groupby.DataFrameGroupBy

然后可以对创建的同一groupby对象执行不同的聚合,以确保不会再次计算索引。

让我知道这是否有帮助

相关问题