Roger Steinberg
Roger Steinberg

Reputation: 1604

qcut to return bin numbers inversely

I am trying to create a column to return bin values (quintiles) but I want it to return the numbers in a descending format (i.e. 5,4,3,2,1)

The current formula I have is:

df['test'] = pd.qcut(df['ColumnA'], q=5, labels= False) + 1

I tried to order my data in DESC and ASC but the result is still the same.

ColumnA test
2   1
2   1
3   2
3   2
4   3
4   3
5   4
5   4
6   5
6   5

I want the test to return the bin numbers in a descending format.

The expected output should like :

ColumnA test        
2   5
2   5
3   4
3   4
4   3
4   3
5   3
5   3
6   1
6   1

Upvotes: 1

Views: 3469

Answers (2)

Arkadiy Poteryaev
Arkadiy Poteryaev

Reputation: 1

df['test'] = pd.qcut(df['ColumnA'], q=5, labels=np.arange(5, 0, -1))

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61920

Expanding on @ayhan comment, do:

df['test'] = 5 - pd.qcut(df['ColumnA'], q=5, labels= False)
print(df)

Output

   ColumnA  test
0        2     5
1        2     5
2        3     4
3        3     4
4        4     3
5        4     3
6        5     2
7        5     2
8        6     1
9        6     1

Upvotes: 3

Related Questions