Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数据帧聚合到多个列的百分位数列中_Python_Pandas - Fatal编程技术网

Python 将数据帧聚合到多个列的百分位数列中

Python 将数据帧聚合到多个列的百分位数列中,python,pandas,Python,Pandas,在福勒。数据帧: 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

在福勒。数据帧:

    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_变量_1位于前33%或前三个百分位的案例数量,以及ps_变量_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

谢谢@Allen!您的输出数据帧可以重新组织为我的问题中指定的格式吗?在您的示例中,您说您需要2列,但在预期的输出中,您显示了3列。我有点不确定你需要什么。对不起,我会更新问题的。我需要3列的输出