【问题标题】:Divide data by decade then plot it seaborn box and whisker将数据除以十年,然后将其绘制成海生盒和晶须
【发布时间】:2018-02-19 13:41:10
【问题描述】:

我有一个熊猫数据框,其中包含从 1871 年到 2015 年相应年份棒球运动员的平均数据。

  index  year     AVG
    0   1871    0.000000
    1   1871    0.271186
    2   1871    0.291971
    3   1871    0.330827
    4   1871    0.325000
    ...     ...     ....
101305  2015    0.262118
101306  2015    0.151515
101307  2015    0.181818
101308  2015    0.100000
101309  2015    0.245600 

我想为十年的平均值创建一个箱须图。因此,1871 - 1880、1881 - 1891..等的情节。我的计划是在这个数据框中创建另一个列,告诉我玩家属于哪个年代,但我无法弄清楚。

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:

    考虑使用带有双斜杠的 Python 整数除法 // 来定位最接近的 10 年倍数,然后计算十年范围。以零结尾的年份应针对前十年进行调整。下面使用随机数据进行演示(为了重现性而播种)。

    import numpy as np
    import pandas as pd
    from matplotlib import pyplot as plt
    import seaborn as sns
    
    np.random.seed(99)
    df = pd.DataFrame({'year': sum([[x]*5 for x in range(1871,2015)], []),
                       'AVG': abs(np.random.randn(720))/10})
    
    # NEAREST 10 FOR DECADE START
    df['decade_start'] = (df['year'] // 10) * 10 + 1
    
    # ADJUST FOR YEARS ENDING IN ZERO
    df.loc[(df['year'] % 10) == 0, 'decade_start'] = df['decade_start'] - 10
    
    # CALCULATE DECADE RANGE
    df['decade_range'] = df['decade_start'].astype('str') + ' - ' + \
                         (df['decade_start'] + 9).astype('str') 
    
    plt.figure(figsize=(15,5))
    sns.boxplot(x="decade_range", y="AVG", data=df)   
    
    plt.show()
    plt.clf()
    plt.close()
    

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多