12

我有一个带有一些列的 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
4

4 回答 4

19

发现这很容易:

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

有趣的是“ pandas.qcut 和 pandas.cut 之间的区别

于 2016-08-16T14:04:53.603 回答
2

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']

这里给出了一种更一般化的解决方案,在这种情况下,人们想要将切割划分为多列

于 2016-12-26T20:40:41.993 回答
1

您可以在现有列上使用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 可能有一种更惯用的方法来实现这一点......但这超出了我的范围

于 2016-07-13T16:02:29.647 回答
0
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]))

我曾经使用过这个,但我想我可以使用分位数

于 2019-02-08T14:17:29.780 回答