Sunday, February 19, 2017

Python: Count occurences in List

1. Histogram

>>> mylist = [1,3,2,5,4,4,2,2,4,2,4,2,4,6,4,5,2]

>>> import matplotlib.pyplot as plt

>>> plt.hist(mylist)
(array([ 1.,  0.,  6.,  0.,  1.,  0.,  6.,  0.,  2.,  1.]), array([ 1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ,  5.5,  6. ]), <a list of 10 Patch objects>)

>>> plt.show()



2. Collection

>>> mylist = [1,3,2,5,4,4,2,2,4,2,4,2,4,6,4,5,2]

>>> mylist
[1, 3, 2, 5, 4, 4, 2, 2, 4, 2, 4, 2, 4, 6, 4, 5, 2]

>>> from collections import Counter

>>> mylist = Counter(mylist)

>>> mylist
Counter({2: 6, 4: 6, 5: 2, 1: 1, 3: 1, 6: 1})

>>> mylist.most_common(3)
[(2, 6), (4, 6), (5, 2)]


3. Bar plot

>>> mylist = [1,3,2,5,4,4,2,2,4,2,4,2,4,6,4,5,2]

>>> mylist
[1, 3, 2, 5, 4, 4, 2, 2, 4, 2, 4, 2, 4, 6, 4, 5, 2]

>>> from collections import Counter

>>> mylist = Counter(mylist)

>>> mylist
Counter({2: 6, 4: 6, 5: 2, 1: 1, 3: 1, 6: 1})

>>> mylist.most_common(3)
[(2, 6), (4, 6), (5, 2)]

>>> import numpy as np

>>> import matplotlib.pyplot as plt

>>> labels, values = zip(*mylist.items())

>>> indexes = np.arange(len(labels))

>>> width = 1

>>> plt.bar(indexes, values, width)
<Container object of 6 artists>

>>> plt.xticks(indexes + width * 0.5, labels)
([<matplotlib.axis.XTick object at 0x000001FB47050400>, <matplotlib.axis.XTick object at 0x000001FB47063E80>, <matplotlib.axis.XTick object at 0x000001FB47056F60>, <matplotlib.axis.XTick object at 0x000001FB470A6A90>, <matplotlib.axis.XTick object at 0x000001FB470AF4E0>, <matplotlib.axis.XTick object at 0x000001FB470AFEF0>], <a list of 6 Text xticklabel objects>)

>>> plt.show()

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.