plt.hist() only for certain frequency; Python

Viewed 163

I have a huge DataFrame ('df') with different columns from which one stores names as string values ('name'). Now, I would like to simply plot a histogram with the frequency of each name within the DataFrame. However, the data contains thousands of unique names and that's why I would like to only plot a histogram for names from a certain frequency on:

df.name.value_counts() > 100

Can I give this kind of filter/mask to the plot? I already tried to use the 'range' argument in plt.hist():

plt.hist(df['name'], range=[100, 151]);

But it still displays all other names but without their frequency…

1 Answers

The method df.name.value_counts() returns the content of your histogram. This return value can be masked using the usual expressions.

name_frequencies = df.name.value_counts()
most_freq_name_freqs = name_frequencies[name_frequencies > 100]

To draw a histogram of data which is already histogrammed, it is useful to use plt.hist with the weights argument.

plt.hist(most_freq_name_freqs.index, weights=most_freq_name_freqs)

By doing this you create a histogram with a single entry per bin, but the bin content is scaled by the weight. Since the weights are the precomputed frequencies, you get the histogram of name frequencies.

Related