souli
souli

Reputation: 23

Count number of elements in a specific bin

I'm curious on whether its possible to count the number of elements for a specific bin in a histogram, i.e. all elements in ranges 0-10

how would you do this?

e.g. plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100]) would it be possible to count all elements from a dataset that go into bin 0-10

Upvotes: 2

Views: 7696

Answers (2)

MaxNoe
MaxNoe

Reputation: 14987

Matplotlib histograms return the counts for each bin:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.uniform(0, 100, 1000)

counts, edges, plot = plt.hist(x, bins=[0, 10, 20, 50, 100])
print(counts)
print(counts[0]) # first bin

Upvotes: 6

Scott Boston
Scott Boston

Reputation: 153460

Yes, pd.Series.value_counts has bins parameter.

import pandas as pd
s = pd.Series(np.random.randint(0,100,50))
s.value_counts(bins=[0,10,20,30,40,50,60,70,80,90,100]).sort_index()

Output:

(-0.001, 10.0]    8
(10.0, 20.0]      6
(20.0, 30.0]      5
(30.0, 40.0]      6
(40.0, 50.0]      2
(50.0, 60.0]      3
(60.0, 70.0]      4
(70.0, 80.0]      3
(80.0, 90.0]      6
(90.0, 100.0]     7
dtype: int64

Upvotes: 2

Related Questions