john doe john doe - 4 months ago 94
Python Question

How to plot a two column pandas dataframe's elements as an histogram?

I have the following pandas dataframe:

A B

1 3
0 2
1 4
0 1
0 3


I would like to plot the frequency of B instnaces given A, something like this:

|
|
| __
B | | |
| ___ | |
| | | | |
| | | | |
|__|_|__|__|______________
A


Thus, I tried the following:

df2.groupby([df.A, df.B]).count().plot(kind="bar")


However, I am getting the following exception:

TypeError: Empty 'DataFrame': no numeric data to plot


Therefore, my question is how to plot the frequency of the elements in B given the frequency of A?.

Answer

Sounds like this is what you want: You can use Series.value_counts()

print(df['B'].value_counts().plot(kind='bar'))

enter image description here

If you don't want the value_count sorted, you can do this:

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

enter image description here