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
然后可以对同一个分组对象执行不同的聚合操作,确保它不会重新计算索引。
如果这有帮助,请让我知道。