Sort And Limit Number Of Bars To Display On Bargraph
I have a dataset of traffic violations and want to display only the top 10 violations per month on a bargraph.  Can I limit the number of bars after sorting values to display only
Solution 1:
This will work:
month_jan[feature_cols].sum().sort_values(ascending=0)[:10].plot(kind='bar')
Solution 2:
Series objects have a .head method, just like DataFrames (docs).
This allows you to select the top N items very elegantly with data.head(N).
Here's a complete working example:
import pandas as pd
df = pd.DataFrame({
    'feature1': [0, 1, 2, 3],
    'feature2': [2, 3, 4, 5],
    'MonthName': ['Jan', 'Jan', 'Jan', 'Feb']
})
feature_cols = ['feature1', 'feature2']
month_jan = df[df.MonthName == "Jan"]
top10 = month_jan[feature_cols].sum().sort_values(ascending=0).head(10)
top10.plot(kind='bar')
Post a Comment for "Sort And Limit Number Of Bars To Display On Bargraph"