Change Column Data using Pandas

Asked

Viewed 3,264 times

1

I’m trying to learn panda but I’m having 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 Class and with the information "First", "Second" and "Third" according to the numbers 1, 2, 3 respectively.

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

But I couldn’t find a way, I would really appreciate your help!

Thank you,

1 answer

2


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 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
  • Man, you helped me so much! Thank you so much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.