将数据除以十年,然后绘制出seaborn box和whis

2024-04-29 19:56:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,显示了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 

我想创建一个十年平均值的方框图。我的计划是在这个数据框中创建一个列,告诉我一个玩家属于哪个年代,但是我不知道。在


Tags: 数据pandasindex玩家year计划avg平均值
1条回答
网友
1楼 · 发布于 2024-04-29 19:56:19

考虑使用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()

Box Plot Output

相关问题 更多 >