tel*_*tel 3 python percentile pandas
我有一个 Pandas 数据框,其中每一列代表一个单独的属性,每一行都保存特定日期的属性值:
import pandas as pd
dfstr = \
''' AC BO C CCM CL CRD CT DA GC GF
2010-01-19 0.844135 -0.194530 -0.231046 0.245615 -0.581238 -0.593562 0.057288 0.655903 0.823997 0.221920
2010-01-20 -0.204845 -0.225876 0.835611 -0.594950 -0.607364 0.042603 0.639168 0.816524 0.210653 0.237833
2010-01-21 0.824852 -0.216449 -0.220136 0.234343 -0.611756 -0.624060 0.028295 0.622516 0.811741 0.201083'''
df = pd.read_csv(pd.compat.StringIO(dfstr), sep='\s+')
Run Code Online (Sandbox Code Playgroud)
使用该rank方法,我可以找到每个属性相对于特定日期的百分位排名:
df.rank(axis=1, pct=True)
Run Code Online (Sandbox Code Playgroud)
输出:
AC BO C CCM CL CRD CT DA GC GF
2010-01-19 1.0 0.4 0.3 0.7 0.2 0.1 0.5 0.8 0.9 0.6
2010-01-20 0.4 0.3 1.0 0.2 0.1 0.5 0.8 0.9 0.6 0.7
2010-01-21 1.0 0.4 0.3 0.7 0.2 0.1 0.5 0.8 0.9 0.6
Run Code Online (Sandbox Code Playgroud)
我想得到的是每个属性的分位数(例如四分位数、五分位数、十分位数等)等级。例如,对于五分位数,我想要的输出是:
AC BO C CCM CL CRD CT DA GC GF
2010-01-19 5 2 2 4 1 1 3 4 5 3
2010-01-20 2 2 5 1 1 3 4 5 3 4
2010-01-21 5 2 2 4 1 1 3 4 5 3
Run Code Online (Sandbox Code Playgroud)
我可能遗漏了一些东西,但似乎没有内置的方法可以用 Pandas 进行这种分位数排名。获得所需输出的最简单方法是什么?
mul&np.ceil你和军衔很接近。只需乘以 5.mul即可获得所需的分位数,同时四舍五入np.ceil:
np.ceil(df.rank(axis=1, pct=True).mul(5))
Run Code Online (Sandbox Code Playgroud)
Output
AC BO C CCM CL CRD CT DA GC GF
2010-01-19 5.0 2.0 2.0 4.0 1.0 1.0 3.0 4.0 5.0 3.0
2010-01-20 2.0 2.0 5.0 1.0 1.0 3.0 4.0 5.0 3.0 4.0
2010-01-21 5.0 2.0 2.0 4.0 1.0 1.0 3.0 4.0 5.0 3.0
Run Code Online (Sandbox Code Playgroud)
如果你想要整数使用astype:
np.ceil(df.rank(axis=1, pct=True).mul(5)).astype(int)
Run Code Online (Sandbox Code Playgroud)
甚至更好
。由于大熊猫版本0.24.0我们有空整数类型:Int64。
所以我们可以使用:
np.ceil(df.rank(axis=1, pct=True).mul(5)).astype('Int64')
Run Code Online (Sandbox Code Playgroud)
Output
AC BO C CCM CL CRD CT DA GC GF
2010-01-19 5 2 2 4 1 1 3 4 5 3
2010-01-20 2 2 5 1 1 3 4 5 3 4
2010-01-21 5 2 2 4 1 1 3 4 5 3
Run Code Online (Sandbox Code Playgroud)
scipy.stats.percentileofscored = df.apply(lambda x: [np.ceil(stats.percentileofscore(x, a, 'rank')*0.05) for a in x], axis=1).values
pd.DataFrame(data=np.concatenate(d).reshape(d.shape[0], len(d[0])),
columns=df.columns,
dtype='int',
index=df.index)
Run Code Online (Sandbox Code Playgroud)
Output
AC BO C CCM CL CRD CT DA GC GF
2010-01-19 5 2 2 4 1 1 3 4 5 3
2010-01-20 2 2 5 1 1 3 4 5 3 4
2010-01-21 5 2 2 4 1 1 3 4 5 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1502 次 |
| 最近记录: |