Histogram of one field wrt another in pandas python

十年热恋 提交于 2020-07-10 03:30:20

问题


I am trying to plot a histogram distribution of one column with respect to another. For example, if the dataframe columns are ['count','age'], then I want to plot the total counts in each age group. Suppose in

age: 0-10 -> total count was 20

age: 10-20 -> total count was 10

age: 20-30 -> ... etc

I tried groupby('age') and than plotting histogram but it didn't work.

Thanks.

Update

Here is some of my data

df.head()
   age    count
0   65  2417.86
1   65  4173.50
2   65  3549.16
3   65   509.07
4   65     0.00

Also, df.plot( x='age', y='count', kind='hist') shows

degree/count histogram plot


回答1:


Ok,if I understand correctly, you want a weighted histogram

import pylab as plt
import pandas as pd
np = pd.np

df = pd.DataFrame( {'age':np.random.normal( 50,10,300).astype(int),
                    'counts':1000*np.random.random(300)} ) # test data
#df.head()
#   age      counts
#0   38  797.174450
#1   36  402.171434
#2   49  894.218420
#3   66  841.786623
#4   51  597.040259

df.hist('age',weights=df['counts'] )
plt.ylabel('counts')
plt.show()

yields the figure



来源:https://stackoverflow.com/questions/31780893/histogram-of-one-field-wrt-another-in-pandas-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!