[英]How to plot a two column pandas dataframe's elements as an histogram?
我有以下pandas數據幀:
A B
1 3
0 2
1 4
0 1
0 3
我想繪制給定A的B實例的頻率,如下所示:
|
|
| __
B | | |
| ___ | |
| | | | |
| | | | |
|__|_|__|__|______________
A
因此,我嘗試了以下內容:
df2.groupby([df.A, df.B]).count().plot(kind="bar")
但是,我得到以下異常:
TypeError: Empty 'DataFrame': no numeric data to plot
因此,我的問題是如何根據A?的頻率繪制B中元素的頻率。
這聽起來像你想要的:你可以使用Series.value_counts()
print(df['B'].value_counts().plot(kind='bar'))
如果您不希望value_count
排序,則可以執行以下操作:
print(df['B'].value_counts(sort=False).plot(kind='bar'))
我不完全確定你的意思是“根據A的頻率繪制B中元素的頻率”,但這給出了預期的輸出:
In [4]: df
Out[4]:
A B
3995 1 3
3996 0 2
3997 1 4
3998 0 1
3999 0 3
In [8]: df['data'] = df['A']*df['B']
In [9]: df
Out[9]:
A B data
3995 1 3 3
3996 0 2 0
3997 1 4 4
3998 0 1 0
3999 0 3 0
In [10]: df[['A','data']].plot(kind='bar', x='A', y='data')
Out[10]: <matplotlib.axes._subplots.AxesSubplot at 0x7fde7eebb9e8>
In [11]: plt.show()
我相信如果您試圖繪制b列中值的出現頻率,這可能會有所幫助。
from collections import Counter
vals = list(df['b'])
cntr = Counter(vals)
# Out[30]: Counter({1: 1, 2: 1, 3: 2, 4: 1})
vals = [(key,cntr[key]) for key in cntr]
x = [tup[0] for tup in vals]
y = [tup[1] for tup in vals]
plt.bar(x,y,label='Bar1',color='red')
plt.show()
另一種使用matplotlib
histogram
方法。 首先聲明一個bin數組,它基本上是你的值將進入的桶。
import matplotlib.pyplot as plt
import pandas as pd
l = [(1,3),(0,2),(1,4),(0,1),(0,3)]
df = pd.DataFrame(l)
df.columns = ['a','b']
bins = [1,2,3,4,5] #ranges of data
plt.hist(list(df['b']),bins,histtype='bar',rwidth=0.8)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.