-1

In a python program I have a single output. I want the count of all unique values of that output of that program.I do not want to use dataframe because the input size is too big. I am new to python and any help would be appreciated.

  • 4
    please read how to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – kederrac Mar 20 '20 at 10:14

1 Answers1

1

Solution

You can do it using any of the following three methods. Since, you did not provide any working code or dummy data, I made my own. Although the three methods essentially produce the same result, the order of the unique-values printed is different for each method.

Method-1

Using set and list-comprehension with list.count().

# Dummy Data
values = list('abcddanbcaeghfgba')
# expect:
# ('a', 4) ('b', 3) ('c', 2) 
# ('d', 2) ('e', 1) ('f', 1) 
# ('g', 2) ('h', 1) ('n', 1)

# Method-1
unique_values = set(values)
counts = [values.count(e) for e in unique_values]
print(*zip(unique_values, counts))

Output:

('a', 4) ('e', 1) ('g', 2) ('b', 3) ('d', 2) ('h', 1) ('f', 1) ('n', 1) ('c', 2)

Method-2

Using collections.Counter.

from collections import Counter

# Method-2
unique_values = Counter(values).keys() 
counts = Counter(values).values()

print(*zip(unique_values, counts))

Output:

('a', 4) ('b', 3) ('c', 2) ('d', 2) ('n', 1) ('e', 1) ('g', 2) ('h', 1) ('f', 1)

Method-3

Using numpy.unique().

import numpy as np

# Method-3
unique_values, counts = np.unique(values, return_counts=True)

print(*zip(unique_values, counts))

Output:

('a', 4) ('b', 3) ('c', 2) ('d', 2) ('e', 1) ('f', 1) ('g', 2) ('h', 1) ('n', 1)

Reference:

CypherX
  • 7,019
  • 3
  • 25
  • 37