【问题标题】:How to draw a histogram using pandas cut如何使用 pandas cut 绘制直方图
【发布时间】:2020-11-28 04:33:08
【问题描述】:

这是我的数据:

df = pd.DataFrame(myList, index=None, columns=['seconds'])
df['count']= pd.cut(df['seconds'], bins = 30)

Categories (30, interval[float64]): [(0.0871, 0.117] < (0.117, 0.145] < (0.145, 0.174] <
                                     (0.174, 0.202] ... (0.83, 0.858] < (0.858, 0.887] <
                                     (0.887, 0.915] < (0.915, 0.944]]

如何从这个结果中绘制直方图? (x 轴是浮动值,y 是每个桶中值的总数?)我看到很多帖子使用“kind=bar”进行绘制,但我想知道是否可以通过以下方式绘制这些数据使用直方图?

谢谢大家

【问题讨论】:

    标签: python pandas histogram


    【解决方案1】:

    这是一个简单的例子...希望对您有所帮助:

    import random
    df = pd.DataFrame([random.randint(1,1000) for i in range(0,100)], columns=['sec'])
    df['bin']=pd.cut(df['sec'], bins = 30).astype(str)
    df2 = df.groupby('bin').bin.count()
    # Fixed to show distribution of bin
    df2.plot(kind='bar')
    

    输出:

    df2.plot(kind='hist')
    

    bin直方图的输出在这里:

    秒的直方图输出:

    df.sec.plot(kind='hist')
    

    【讨论】:

    • 无论如何我们可以将“计数”作为 y 轴吗?从您的帖子来看,计数位于 x 轴上。
    • @pkim 固定做条形图箱....并且还添加了秒的直方图...
    【解决方案2】:

    使用seaborncountplot函数的答案,使用pandas.cut函数后:

    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    bins = list(range(0, 110, 10))
    bins.append(float('inf'))
    np.random.seed(31415)
    data_age = np.random.randint(low=0, high=120, size=200)
    
    df_test = pd.DataFrame({'age': data_age, 
                            'age_group': pd.cut(data_age, bins=bins, right=False)})
    
    ax = sns.countplot(data=df_test, x='age_group')
    ax.tick_params(axis='x', labelrotation=90)
    

    这构建了这种图像:

    库版本:

    • Numpy:1.18.0
    • 熊猫:1.1.5
    • Seaborn:0.11.0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2020-10-25
      • 2016-07-02
      相关资源
      最近更新 更多