为什么单个框的数据框groupby不返回数据框? [英] Why doesn't dataframe groupby with a single group return a dataframe?

查看:71
本文介绍了为什么单个框的数据框groupby不返回数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑这是我问题的一种简单形式

I suspect this is a simpler form of my question here. [Update: unfortunately not so.]

如果您这样做(在熊猫0.11中):

If you do something like this (in Pandas 0.11):

df = pd.DataFrame([[1,2],[1,3],[2,4]],columns='a b'.split())
print df
g = df.groupby('a').count()
print type(g)
print g

您得到了预期的结果:

   a  b
0  1  2
1  1  3
2  2  4
<class 'pandas.core.frame.DataFrame'>
   a  b
a      
1  2  2
2  1  1

但是如果只有一个结果组,则会得到一个非常奇怪的系列:

But if there's only one resulting group, you get a very odd Series instead:

df = pd.DataFrame([[1,2],[1,3],[1,4]],columns='a b'.split())
...

   a  b
0  1  2
1  1  3
2  1  4
<class 'pandas.core.series.Series'>
a   
1  a    3
   b    3
Name: 1, dtype: int64

但是我希望结果是一个等效于此的DataFrame:

But I'd rather the result was a DataFrame equivalent to this:

print pd.DataFrame([[3,3]],index=pd.Index([1],name='a'),columns='a b'.split())

   a  b
a      
1  3  3

我对如何轻松地从系列中获取它感到困惑(不确定为什么我会首先获得它).

I'm stuck as to how to get that easily from the series (and not sure why I get that in the first place).

推荐答案

在熊猫0.12中,这完全符合您的要求.

In pandas 0.12 this does exactly what you ask.

In [3]: df = pd.DataFrame([[1,2],[1,3],[1,4]],columns='a b'.split())

In [4]: df.groupby('a').count()
Out[4]:
   a  b
a
1  3  3

要复制您看到的通行证squeeze=True:

To replicate what you're seeing pass squeeze=True:

In [5]: df.groupby('a', squeeze=True).count()
Out[5]:
a
1  a    3
   b    3
Name: 1, dtype: int64

如果您无法升级,请执行以下操作:

If you can't upgrade then do:

In [3]: df.groupby('a').count().unstack()
Out[3]:
   a  b
a
1  3  3

这篇关于为什么单个框的数据框groupby不返回数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆