根据前几年的数据计算 pandas 数据框行的百分位数 [英] Compute percentile for pandas dataframe row based on previous years data

查看:74
本文介绍了根据前几年的数据计算 pandas 数据框行的百分位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

datetime       JD      YEAR    VAL 
2000-01-01      1      2000    0.5
2000-01-02      2      2000    1.2
2000-01-03      3      2000    2.1
2000-01-04      4      2000    3.4 
2000-01-05      5      2000    4.6
2000-01-06      6      2000    6.8
2000-01-07      7      2000    7.2
2000-01-08      8      2000    0.2
2000-01-09      9      2000    0.9
...
2010-12-31      365    2014    4.1

第一年是2000年,去年是2010年.没有leap年(即,没有对应于2月29日的行),datetime是索引列.

The first year is 2000 and last year is 2010. There are no leap years (i.e. no row corresponding to Feb 29th), datetime is the index column.

我想计算一个从2010年1月1日到2010年12月31日的新数据帧.我希望它包含一个列,该列计算由10个值组成的数组中2010年1月1日值(VAL)的百分位数( 2000年1月1日,2001年1月1日... 2009年1月1日).同样,将2010年1月2日与往年的1月2日进行比较....

I would like to compute a new dataframe, stretching from Jan 1st 2010 to Dec 31st 2010. I would like it to contains a column which computes the percentile of Jan 1st 2010 value (VAL) in the array composed of 10 values (Jan 1st 2000, Jan 1st 2001...Jan 1st 2009). Similarly, Jan 2nd 2010 is compared against Jan 2nd from previous years....

lyr = df.YEAR.max() # last year i.e. 2010
cdf = df[df.YEAR == lyr]# Latest year dataframe
pdf = df[df.index.year < lyr] # Previous years dataframe

pdf.groupby('JD')['VAL']
stats.percentileofscore(pdf['VAL'], cdf['VAL'])

但是,我不确定如何使代码正常工作. groupby只返回group,而我需要一个值列表.

However, I am not sure how to get the code to work. The groupby only returns group whereas I need a list of values.

推荐答案

设置一个小的示例数据框:

Set up with a small sample dataframe:

np.random.seed(1234)
df = pd.DataFrame({ 'jd':  np.tile([1,2],3),
                    'yr':  np.repeat([2008,2009,2010],2),
                    'val': np.random.randn(6) })

那只是一行:

df['pctile'] = df.groupby('jd')['val'].rank(pct=True)

这是输出,按sort_values(['jd','val'])

   jd       val    yr    pctile
4   1 -0.720589  2010  0.333333
0   1  0.471435  2008  0.666667
2   1  1.432707  2009  1.000000
1   2 -1.190976  2008  0.333333
3   2 -0.312652  2009  0.666667
5   2  0.887163  2010  1.000000

这篇关于根据前几年的数据计算 pandas 数据框行的百分位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆