将熊猫数据框聚合为多列的百分位数
问题描述:
在下面的表格中。 dataframe:将熊猫数据框聚合为多列的百分位数
ps_variable_2 ps_variable_1
0 45.652174 60.000000
1 48.913043 13.333333
2 56.521739 55.555556
3 57.608696 37.777778
4 30.434783 44.444444
5 36.956522 77.777778
6 33.695652 64.444444
7 53.260870 37.777778
我想从中得到一个新的数据框,其中有3列:前33%中33%下33%。每列有3行如下:
Top 33% Middle 33% Bottom 33%
Top 33%
Middle 33%
Bottom 33%
例如,第一行包含ps_variable_1处于前33%或前三分之一的情况的数量,以及ps_variable_2分别处于前三分之一,中三分之一和下三分之一的情况的相应数量。
答
您可以使用排名获得每行的百分位数,将它们切到顶部,中间底部的箱子,然后对它们进行计数。
(
df.apply(lambda x: pd.cut(x.rank(pct=True),
[0,1/3.0,2/3.0,1],
labels=["Bottom 33%","Middle 33%","Top 33%"]))
.apply(lambda y: y.value_counts())
)
Out[549]:
ps_variable_2 ps_variable_1
Bottom 33% 2 3
Middle 33% 3 2
Top 33% 3 3
谢谢@艾伦!你的输出数据框可以重新组织成我的问题中指定的格式吗? – user308827
在你的例子中,你说你需要2列,但在预期的输出中,你显示了3列。我有点不确定你需要什么。 – Allen
对不起,我会更新问题。我需要输出3列 – user308827