Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't dataframe groupby with a single group return a dataframe?

Tags:

python

pandas

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

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

You get the expected:

   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

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).

like image 666
patricksurry Avatar asked Sep 11 '26 19:09

patricksurry


1 Answers

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

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
like image 117
Phillip Cloud Avatar answered Sep 14 '26 00:09

Phillip Cloud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!