在Python中,从一个大的、单个的数据集中创建多个直方图,按用户分组
我有一个大数据集,df:在Python中,从一个大的、单个的数据集中创建多个直方图,按用户分组,python,pandas,numpy,matplotlib,Python,Pandas,Numpy,Matplotlib,我有一个大数据集,df: User duration amy 582 amy 27 amy 592 amy 16 amy 250 tom 33 tom 10 tom 40 t
User duration
amy 582
amy 27
amy 592
amy 16
amy 250
tom 33
tom 10
tom 40
tom 100
我想按用户分组,然后为每个用户创建直方图:
amy (histogram image)
tom (histogram image)
以下是dput:
structure(list(User = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L), .Label = c("amy", "tom"), class = "factor"), duration = c(582L,
27L, 592L, 16L, 250L, 33L, 10L, 40L, 100L)), class = "data.frame", row.names = c(NA,
-9L))
我知道如何使用以下代码在Python中创建直方图:,但如何在Python中创建多个直方图,并按用户分组。我应该编一本字典吗
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
df = (amy[582,27, 592, 16, 250], tom[33,10,40,100])
num_bins = 20
n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
plt.show()
如有任何建议,我们将不胜感激
df = pd.DataFrame({'user':['amy', 'amy','amy','amy','amy', 'tom', 'tom', 'tom','tom',],
'duration': [582, 27, 592, 16, 250, 33, 10, 40, 100]})
ax = df['duration'].hist(by=df['user'])
for a in ax.flatten():
a.set_xlabel("duration")
a.set_ylabel("frequency")
让我试试。非常感谢。