9

OK so I have six possible values for data to be which are '32', '22', '12', '31', '21' and '11'. I have these stored as strings. Is it possible for python to sort through the data and just make six bins and show how many of each I have? Or do the inputs to a histogram HAVE to be numerical?

Catherine Georgia
  • 879
  • 3
  • 13
  • 17
  • 3
    There is a difference between a bar graph and a histogram. A bar graph is appropriate here, while a histogram is not. – Waleed Khan Oct 31 '12 at 11:17
  • OK but if I used a bar graph would I have to manually sort through each piece of data to determine which category it was in before plotting? Is there a way of getting it to sort it for me like the histogram does? – Catherine Georgia Oct 31 '12 at 11:19
  • What do you mean by "like the histogram does"? Is there a Python histogram library I don't know about? – Waleed Khan Oct 31 '12 at 11:22
  • If you have a list of strs you can convert them to ints fairly easily: `listOfInts = map(int,listOfStrs)` – Matt Oct 31 '12 at 11:44
  • Check this post: http://stackoverflow.com/questions/7871338/creating-bar-charts-in-python after following Matts advice (converting all to ints). –  Oct 31 '12 at 11:49

4 Answers4

15
data =  ['32', '22', '12', '32', '22', '12', '31', '21', '11']
dict((x, data.count(x)) for x in data)

Result

{'11': 1, '12': 2, '21': 1, '22': 2, '31': 1, '32': 2}
7

Did you consider using collections.Counter?

# python 2.7
>>> l = ['32', '22', '12', '31', '21', '11', '32']
>>> import collections
>>> collections.Counter(l)
Counter({'32': 2, '11': 1, '12': 1, '21': 1, '22': 1, '31': 1})
GilZ
  • 6,418
  • 5
  • 30
  • 40
2
data =  ['32', '22', '12', '32', '22', '12', '31', '21', '11']
sm = {i:0 for i in ['32', '22', '12', '31', '21','11']}
for i in data:
    sm[i] += 1
print sm

Something like this?

f p
  • 3,165
  • 1
  • 27
  • 35
0

Assuming data is a list and you want to count the numbers in a bins. I will use bins as a dictionary.

bin = {'11': 0, '12': 0, '21': 0, '22': 0, '31': 0, '32': 0}

for element in data:
    if element in bin:  # Ignore other elements in data if any
        bin[element] = bin[element] + 1

bins dictionary will have frequency of each element in data list. Now you can use bins to plot bar graph using graph plot library. May be you can use this post to check matplotlib usage for plotting bar graph.

Community
  • 1
  • 1
  • 1
    List comprehension is Pythonic, explicit looping is not. –  Oct 31 '12 at 12:55
  • People are confused about what is pythonic - it means "easy to write, read and understand in Python" or "idiomatic Python". Your code is idiomatic C/Java/... –  Oct 31 '12 at 12:58
  • And you claim that this code doesn't obey this definition is wrong. –  Oct 31 '12 at 12:59
  • I wouldn't discuss this further. But I disagree with your claim. Thank you. –  Oct 31 '12 at 13:02
  • Also see http://stackoverflow.com/questions/58968/what-defines-pythonian-or-pythonic –  Oct 31 '12 at 13:03