簡體   English   中英

創建多個直方圖,按用戶從 Python 中的大型單個數據集分組

[英]Create multiple histograms, grouped by user from a large, single dataset in Python

我有一個大數據集 df:

  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")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM