0 votes
1 view
in Data Science by (17.6k points)

One last newbie pandas question for the day: How do I generate a table for a single Series?

For example:

my_series = pandas.Series([1,2,2,3,3,3])

pandas.magical_frequency_function( my_series )

>> {

     1 : 1,

     2 : 2, 

     3 : 3

   }

Lots of googling has led me to Series.describe() and pandas.crosstabs, but neither of these does quite what I need: one variable, counts by categories. Oh, and it'd be nice if it worked for different data types: strings, ints, etc.

1 Answer

0 votes
by (41.4k points)

Using .value_counts()

>>> import pandas

>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])

>>> my_series

0       1

1       2

2       2

3       3

4       3

5       3

6    fred

7     1.8

8     1.8

>>> counts = my_series.value_counts()

>>> counts

3       3

2       2

1.8     2

fred    1

1       1

>>> len(counts)

5

>>> sum(counts)

9

>>> counts["fred"]

1

>>> dict(counts)

{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

If you are interested to learn Pandas visit this Python Pandas Tutorial.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !

Categories

...