python - 我怎样才能有效地获得[许多]四分位数?

标签 python pandas percentile data-preprocessing quartile

我需要按范围对数值进行编码:低:0,中:1,高:2,非常高:3。我正在为四分位数进行编码。我有以下代码:

import pandas as pd
import numpy as np

def fun(df):
    table = df.copy() # pandas dataframe
    N = int(table.shape[0])
    for header in list(table.columns):
        q1 = np.percentile(table[header], 25)
        q2 = np.percentile(table[header], 50)
        q3 = np.percentile(table[header], 75)
        for k in range(0, N):
            if( table[header][k] < q1 ):
                table[header][k] = int(0)
            elif( (table[header][k] >= q1) & (table[header][k] < q2)):
                table[header][k] = int(1)
            elif( (table[header][k] >= q2) & (table[header][k] < q3)):
                table[header][k] = int(2)
            else:
                table[header][k] = int(3)
        pass
    table = table.astype(int)
    return table

证明

df = pd.DataFrame( {
        'A': [30, 28, 32, 25, 25, 25, 22, 24, 35, 40],
        'B': [25, 30, 27, 40, 42, 40, 50, 45, 30, 25],
        'C': [25.5, 30.1, 27.3, 40.77, 25.1, 25.34, 22.11, 23.81, 33.66, 38.56],
    }, columns = [ 'A', 'B', 'C' ] )

结果:

A  B  C
2  0  1
2  1  2
3  0  2
1  2  3
1  3  0
1  2  1
0  3  0
0  3  0
3  1  3
3  0  3

有什么方法可以有效地做到这一点?

最佳答案

您可以结合使用 np.digitizepd.rank

In [569]: np.digitize(df.rank(pct=True), bins=[.25, .5, .75], right=True)
Out[569]:
array([[2, 0, 1],
       [2, 1, 2],
       [3, 1, 2],
       [1, 2, 3],
       [1, 3, 1],
       [1, 2, 1],
       [0, 3, 0],
       [0, 3, 0],
       [3, 1, 3],
       [3, 0, 3]], dtype=int64)

详细信息

In [570]: df.rank(pct=True)
Out[570]:
     A     B    C
0  0.7  0.15  0.5
1  0.6  0.45  0.7
2  0.8  0.30  0.6
3  0.4  0.65  1.0
4  0.4  0.80  0.3
5  0.4  0.65  0.4
6  0.1  1.00  0.1
7  0.2  0.90  0.2
8  0.9  0.45  0.8
9  1.0  0.15  0.9

In [571]: pd.DataFrame(np.digitize(df.rank(pct=True), bins=[.25, .5, .75], right=True),
                       columns=df.columns)
Out[571]:
   A  B  C
0  2  0  1
1  2  1  2
2  3  1  2
3  1  2  3
4  1  3  1
5  1  2  1
6  0  3  0
7  0  3  0
8  3  1  3
9  3  0  3

关于python - 我怎样才能有效地获得[许多]四分位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42207500/

相关文章:

python - 使用 Numeric Python 的数组的逐元素中值和百分位数

c++ - Matlab 到 C++ 代码转换

python - 从 kubernetes-incubator/client-python 连接到 gke 集群时出错

Python Pandas 使用日期时间数据按日期分组

python - 如何在 wxPython 网格中禁用可调整大小的行?

python - 如何组合多个列并创建唯一的数值

python - 如何获取 pandas df.plot() 中最近绘制的线的颜色

java - 95% 如何确定客户端上的默认超时设置?

python - 从列表中的列表创建矩阵

python - Pygame 当您按下键时将图像移动到位置