Change column data using Pandas

0

I'm trying to learn panda but I have a question here

I have the following data:

PSG    CLASS   
AAA     1  
BBB     2 
CCC     3 
DDD     1

I wanted to create a new column, using Pandas, with the name of Class and with the information of "First," "Second" and "Third" according to numbers 1, 2, 3 respectively.

Basically I wanted to create something like "If CLASS = 1 then the CLASS column gets FIRST"

But I could not find how to do it, I would greatly appreciate your help!

Thanks,

    
asked by anonymous 09.08.2018 / 21:01

1 answer

0

Starting from the example:

import pandas as pd

d = {'PSG':['AAA', 'BBB', 'CCC', 'DDD'], 'CLASS':[1,2,3,1]}
df = pd.DataFrame(data=d)

>>> print df
   CLASS  PSG
0      1  AAA
1      2  BBB
2      3  CCC
3      1  DDD

We created a rule to define the classes

def define_classe(num):
    if num == 1:
        return 'PRIMEIRO'
    elif num == 2:
        return 'SEGUNDO'
    elif num == 3:
        return 'TERCEIRO'
    return 'SEM_CLASSE'

And then we apply the rule

df['CLASSE'] = df['CLASS'].map(define_classe)

>>> print df
   CLASS  PSG    CLASSE
0      1  AAA  PRIMEIRO
1      2  BBB   SEGUNDO
2      3  CCC  TERCEIRO
3      1  DDD  PRIMEIRO
    
09.08.2018 / 21:19