0

I have a list in a file of different animals which is opened and read in a function.

For example my list is:

Cats, Dogs, Cows, Cows, Cows, Sheep, Dogs, Sheep, etc.

How do I put these in a list which will group the same animals together and return the number of each animal in the list, for example for this list I want:

List = (1, 2, 3, 2)

This will then enable me to work out the length of this new list and give how many different animals there are.

Without using sets if possible.

Also, because it is in a function I cant be specific about each animal.

Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
  • Possible duplicate of [Fastest way to count number of occurrences in a Python list](https://stackoverflow.com/questions/12452678/fastest-way-to-count-number-of-occurrences-in-a-python-list) – Thomas Mar 18 '19 at 18:07

3 Answers3

1

You can use the values of a collections.Counter object instantiated from the list:

from collections import Counter
l = ['Cats', 'Dogs', 'Cows', 'Cows', 'Cows', 'Sheep', 'Dogs', 'Sheep']
print(list(Counter(l).values()))

This outputs:

[1, 2, 3, 2]
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

The below uses pandas to create a DataFrame with your list.

You can then use the pandas value_counts function, which returns a Series containing counts of unique Animals.

import pandas as pd

myAnimals = {'Animals': ['Cats', 'Dogs', 'Cows', 'Cows', 'Cows', 'Sheep', 'Dogs', 'Sheep']}
myList = pd.DataFrame(myAnimals)

pd.value_counts(myList['Animals'].values)

I find the output of this method more straight-forward:

Cows     3
Sheep    2
Dogs     2
Cats     1

See value_counts for more information.

  • 1
    Please provide some explanation regarding your code. It's always better to give some textual description about your solution instead of merely throwing code at OP. – Szymon Maszke Mar 18 '19 at 18:44
  • 1
    Added additional explanation. Thanks for the feedback. @Szymon. This was my first response on stackoverflow. – drumstick2121 Mar 18 '19 at 19:24
0

You could use groupby from pandas

    import pandas as pd

    listOfAnimalsDF = pd.DataFrame({"Animal": ["Cats", "Dogs", "Cows", "Cows", "Cows", "Sheep", "Dogs", "Sheep"]})
    grouped = listOfAnimalsDF.groupby(by="Animal")

    print(grouped.groups)

For more Information about the pandas.DataFrame.groupby

Bortoli
  • 9
  • 3