I have a dataframe:
index zip lat lng city state_id state_name population density county_name timezone
0 0 01001 42.0626 -72.6259 Agawam MA Massachusetts 16769 565.8 Hampden America/New_York
1 1 01002 42.3749 -72.4621 Amherst MA Massachusetts 29049 203.8 Hampshire America/New_York
2 2 01003 42.3919 -72.5248 Amherst MA Massachusetts 10372 5629.7 Hampshire America/New_York
3 3 01005 42.4202 -72.1061 Barre MA Massachusetts 5079 44.3 Worcester America/New_York
4 4 01007 42.2787 -72.4003 Belchertown MA Massachusetts 14649 107.4 Hampshire America/New_York
... ... ... ... ... ... ... ... ... ... ... ...
460 531 02771 41.8379 -71.3174 Seekonk MA Massachusetts 13708 288.1 Bristol America/New_York
461 532 02777 41.7570 -71.2121 Swansea MA Massachusetts 15840 269.7 Bristol America/New_York
462 533 02779 41.8349 -71.0754 Berkley MA Massachusetts 6411 149.9 Bristol America/New_York
463 534 02780 41.9076 -71.1196 Taunton MA Massachusetts 49036 573.1 Bristol America/New_York
464 535 02790 41.5999 -71.0832 Westport MA Massachusetts 15717 113.0 Bristol America/New_York
465 rows × 11 columns
I have to plot a histogram of cities and their populations. So, I used the following code from this answer:
import pylab as plt
ma_hist = ma_StateData.hist('city',weights=ma_StateData['population'] )
plt.ylabel('population')
plt.show()
This yields an error:
ValueError: hist method requires numerical columns, nothing to plot.
I also tried by the documentation:
ma_StateData.columns
# ma_histogram = pd.DataFrame.hist(ma_StateData, column='city', by='population')
# ma_histogram.plot.hist()
ma_city_population = ma_StateData[['city','population']]
ma_city_population.plot.hist(by='city')
But the resulting histogram is not correct(not what I am looking for):

What I want is a histogram whose x axis is cities, and corresponding to each city, the bar shows the population of that city.
How do I do that?
I only copied the first 5 rows of your data, I am not sure if you really need histogram, you could do it with groupby and sort_values:
>>> df.groupby('city')['population'].sum().sort_values(ascending=False).plot(kind='bar')

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With