2

I'm very familiar with how to return value_counts from a pd.Series. However, how would I get the value counts from values of a dictionary?

Say that I have the following tuples in dictionary L:

L = {1: (13600, 14797),
     2: (14700, 14700),
     3: (14700, 10400),
     4: (14600, 17200),
     5: (13600, 14797),
     6: (14600, 17200),
     7: (14700, 10400),
     8: (14700, 10400),
     9: (12800, 14770)}

How do I get the value_counts from L that would look like:

(14700, 10400) 3
(13600, 14797) 2
(14600, 17200) 2
(14700, 14700) 1
(12800, 14770) 1

This is what I have so far. However, I think the dictionary keys 1-9 are getting in the way because I get the error list object is not callable.

list = [(k, v) for k, v in L.items()] 
S = set(L)
F = {}
for i in list(S):
    F[i] = list.count(i)
Georgy
  • 12,464
  • 7
  • 65
  • 73
JAG2024
  • 3,987
  • 7
  • 29
  • 58

4 Answers4

7

Use collections.Counter from the standard library:

Counter(L.values())
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
2

Maybe using from collections import Counter is a good idea?

from collections import Counter 
dict(Counter([j for i,j in L.items()]))
snowneji
  • 1,086
  • 1
  • 11
  • 25
2

You can try this:

L = {1: (13600, 14797),
     2: (14700, 14700),
     3: (14700, 10400),
     4: (14600, 17200),
     5: (13600, 14797),
     6: (14600, 17200),
     7: (14700, 10400),
     8: (14700, 10400),
     9: (12800, 14770)}
vals = [ v for v in L.values()]
counts = []
for i in vals:
    counts.append((i, vals.count(i)))
set(counts)
Sultan Singh Atwal
  • 810
  • 2
  • 8
  • 19
2

You mentioned pandas.Series.value_counts(), why did you not try

pd.Series(L).value_counts()

which gives:

(14700, 10400)    3
(14600, 17200)    2
(13600, 14797)    2
(12800, 14770)    1
(14700, 14700)    1
dtype: int64
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74