what is the syntax for Series.groupby(column) equivalent to DataFrame.groupby(column)?

Viewed 56

I am trying to perform a groupby to a series, grouping by the values. e.g. count(). Suppose:

ser = pd.Series({'a': 'aa', 'b': 'bb', 'c': 'ff', 'd': 'ff'})
ser.name= 'foo'
ser.index.name= 'idx'

so ser is:

idx
a    aa
b    bb
c    ff
d    ff
Name: foo, dtype: object

I could do:

>collections.Counter(ser)
Counter({'aa': 1, 'bb': 1, 'ff': 2})

Or:

>print(pd.DataFrame(ser).reset_index().groupby('foo').count())
     idx
foo     
aa     1
bb     1
ff     2

My question is could I / how would I do the same only using Series.groupby(?????).count() ?

Edit: Thank you both for answering this, got to learn two new things today :) +1 to both! I am going to accept @jezrael 's answer as it is more exact, plus it allows me to solve my more complex problem I simplified to get to the question (get the list of all instances in addition to counting them):

>ser.groupby(ser).apply(lambda df:set(df.index))
foo
aa       {a}
bb       {b}
ff    {c, d}
Name: foo, dtype: object
2 Answers

IIUC, there's nothing to apply the groupby on when you're dealing with a series, so you can just count its values.

Would this do?

ser.value_counts()

ser.value_counts()
 
ff    2
aa    1
bb    1

Series has no column, but so you can pass Series like:

print (ser.groupby(ser).count())
foo
aa    1
bb    1
ff    2
Name: foo, dtype: int64
Related