DaveM
DaveM

Reputation: 147

Draw an histogram from pandas column with datetype

I have a dataframe like this:

df = pd.DataFrame({ 'A': ['a','b','c','d','e'],
                    'B': ['1970','1970','1980','1980','1972']
                    })

I converted column B to datetime:

df['B'] = pd.to_datetime(pd.DatetimeIndex(df.B).year, format='%Y')

 Out[13]: 
       A          B
    0  a 1970-01-01
    1  b 1970-01-01
    2  c 1980-01-01
    3  d 1980-01-01
    4  e 1972-01-01

Now I want to draw an histogram that shows year on x-axis and count on the y-axi i.e. for 1970 hist should show 2, for 1980 hist should show 2 and so on. How to do this...

Upvotes: 1

Views: 77

Answers (1)

Scott Boston
Scott Boston

Reputation: 153510

You can do this:

df = pd.DataFrame({ 'A': ['a','b','c','d','e'],
                    'B': ['1970','1970','1980','1980','1972']
                    })
df['B'].hist(grid=False)

Output:

enter image description here

OR

df['B'].value_counts(sort=False).plot.bar()

Output:

enter image description here

And

df = pd.DataFrame({ 'A': ['a','b','c','d','e'],
                    'B': ['1970','1970','1980','1980','1972']
                    })
df['B'] = pd.to_datetime(pd.DatetimeIndex(df.B).year, format='%Y')
df['B'].dt.year.value_counts(sort=False).plot.bar()

Output:

enter image description here

Upvotes: 2

Related Questions