DataFrame:添加值为现有列的分位数 number/rank 的列?

DataFrame: add column whose values are the quantile number/rank of an existing column?

我有一个包含一些列的 DataFrame。我想添加一个新列,其中每一行值是一个现有列的分位数排名。

我可以用DataFrame.rank对一列进行排名,但是我不知道如何获取这个排名值的分位数并将这个分位数添加为一个新的列。

示例:如果这是我的 DataFrame

df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]), columns=['a', 'b'])

   a    b
0  1    1
1  2   10
2  3  100
3  4  100

并且我想知道 b 列的分位数(使用 2 个分位数)。我希望得到这样的结果:

   a    b  quantile
0  1    1    1
1  2   10    1
2  3  100    2
3  4  100    2

您可以在现有列上使用 DataFrame.quantile 和 q=[0.25, 0.5, 0.75] 来生成四分位数列。

然后,您可以 DataFrame.rank 在该四分位数列上。

请参阅下面的添加四分位数列的示例:

import pandas as pd

d = {'one' : pd.Series([40., 45., 50., 55, 60, 65], index=['val1', 'val2', 'val3', 'val4', 'val5', 'val6'])}
df = pd.DataFrame(d)

quantile_frame = df.quantile(q=[0.25, 0.5, 0.75])
quantile_ranks = []
for index, row in df.iterrows():
    if (row['one'] <= quantile_frame.ix[0.25]['one']):
        quantile_ranks.append(1)
    elif (row['one'] > quantile_frame.ix[0.25]['one'] and row['one'] <= quantile_frame.ix[0.5]['one']):
        quantile_ranks.append(2)
    elif (row['one'] > quantile_frame.ix[0.5]['one'] and row['one'] <= quantile_frame.ix[0.75]['one']):
        quantile_ranks.append(3)
    else:
        quantile_ranks.append(4)

df['quartile'] = quantile_ranks

注意:Pandas 可能有更惯用的方法来完成此操作......但它超出了我的范围

很简单:

df['quantile'] = pd.qcut(df['b'], 2, labels=False)

   a    b  quantile
0  1    1         0
1  2   10         0
2  3  100         1
3  4  100         1

有趣的是“

df['quantile'] = pd.qcut(df['b'], 2, labels=False) 似乎倾向于抛出 SettingWithCopyWarning.

我发现唯一的通用方法是:

quantiles = pd.qcut(df['b'], 2, labels=False)
df = df.assign(quantile=quantiles.values)

这会将分位数等级值指定为新的 DataFramedf['quantile']

A solution for a more generalized case, in which one wants to partition the cut by multiple columns, is given here.

df.sort_values(['b'],inplace = True)
df.reset_index(inplace = True,drop = True)
df.reset_index(inplace = True)
df.rename(columns = {'index':'row_num'},inplace = True)
df['quantile'] = df['row_num'].apply(lambda x: math.ceil(10*(x+1)/df.shape[0]))

我以前用这个,但我想我可以用分位数