Home > Software design >  How to re order DF Using pd.Categorical?
How to re order DF Using pd.Categorical?

Time:09-22

Having a DF

Test WGT
TOTO 5
TATA 7
TZTZ 1

doing :

DF['Test'] = pd.Categorical(DF['Test'],categories = ["TATA","TZTZ","TOTO"],ordered=True)

but when I do :

print(DF)

I still have the same DF :

Test WGT
TOTO 5
TATA 7
TZTZ 1

Where the excepted output is :

Test WGT
TATA 7
TZTZ 1
TOTO 5

What am I doing wrong there ?

It seems to me that index has not been reseted :

print(DF.Test)
#returns
0       TOTO
1       TATA
2       TZTZ
    Name: Test, dtype: category
Categories (3, object): ['TATA' < 'TZTZ' < 'TOTO']

CodePudding user response:

You made the values ordered, not sorted.

Now you need to sort_values!

DF2 = DF.sort_values(by='Name')

output:

   Name  WGT
1  TATA    7
2  TZTZ    1
0  TOTO    5
  • Related