matplotlib pandas图直方图 Dataframe 索引

pkwftd7m  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(70)

我在pandas中有以下 Dataframe (df):

NetPrice  Units  Royalty
Price                       
3.65    9.13    171    57.60
3.69    9.23     13     4.54
3.70    9.25    129    43.95
3.80    9.49    122    42.76
3.90    9.74    105    38.30
3.94    9.86    158    57.35
3.98    9.95     37    13.45
4.17   10.42     69    27.32
4.82   12.04    176    77.93
4.84   24.22    132    59.02
5.16   12.91    128    60.81
5.22   13.05    129    62.00

字符串
我试图创建一个直方图的指数(“价格”)与y轴的“单位”。我从以下内容开始:

plt.hist(df.index)


这给了我一个绘制价格的直方图。如何将单位添加到y轴?现在,它只是一个“规模”。
谢谢你,谢谢

qoefvg9y

qoefvg9y1#

因为数据已经部分聚合,所以不能直接使用hist()方法。就像@snorthway在评论中说的,你可以用条形图来做到这一点。你只需要先把你的数据放在桶里。我最喜欢的将数据放入bucket的方法是使用pandas cut()方法。
让我们设置一些示例数据,因为您没有提供一些易于使用的数据:

np.random.seed(1)
n = 1000
df = pd.DataFrame({'Price' : np.random.normal(5,2,size=n),
                   'Units' : np.random.randint(100, size=n)})

字符串
让我们把价格放进10个均匀间隔的桶里:

df['bucket'] = pd.cut(df.Price, 10)
print df.head()

      Price  Units           bucket
0  8.248691     98    (7.307, 8.71]
1  3.776487      8  (3.0999, 4.502]
2  3.943656     89  (3.0999, 4.502]
3  2.854063     27  (1.697, 3.0999]
4  6.730815     29   (5.905, 7.307]


现在我们有了一个包含存储桶范围的字段。如果你想给这些桶取其他名字,你可以在优秀的Pandas documentation中阅读。现在我们可以使用Pandas的groupby()方法和sum()来将单位相加:

newdf = df[['bucket','Units']].groupby('bucket').sum()
print newdf
                  Units
bucket                 
(-1.122, 0.295]     492
(0.295, 1.697]     1663
(1.697, 3.0999]    5003
(3.0999, 4.502]   11084
(4.502, 5.905]    15144
(5.905, 7.307]    11053
(7.307, 8.71]      4424
(8.71, 10.112]     1008
(10.112, 11.515]     77
(11.515, 12.917]    122


看起来像个赢家…现在让我们绘制它:

newdf.plot(kind='bar')


x1c 0d1x的数据

zpqajqem

zpqajqem2#

您可以将索引设置为一列,然后像这样hist绘制该列:

df["idx"] = df.index
df["idx"].hist()

字符串

相关问题