Home > Blockchain >  Replace part of string in column DataFrame
Replace part of string in column DataFrame

Time:08-24

Problem: Currently, I have a column of a dataframe with results like 1.Goalkeeper, 4.Midfield...and I can't change partially replace the string.

Objective: My goal is to replace it with 1.GK, 4.MD...but it doesn't make the replacement. It seems as if these lines are not written. Any ideas?

The code works if the input is the same as the replacement. For example, Goalkeeper, Midfield... but it doesn't work when I prefix it with ( number dot).

CODE

df2['Posicion'].replace({'Goalkeeper':'GK','Left-Back':'LI','Defensive Midfield':'MCD'
,'Right Midfield':'MD','Attacking Midfield':'MP','Right Winger':'ED','Centre-Forward':'DC',
'Centre-Back':'DFC','Right-Back':'LD','Central Midfield':'MC','Second Striker':'SD',
'Left Midfield':'MI','Left Winger':'EI','N':'','None':'','Sweeper':'DFC'}, inplace=True)

CodePudding user response:

regex=True will do the trick here.

df2 = pd.DataFrame({
    'Posicion' : ['1.Goalkeeper', '2.Midfield', '3.Left Winger']
})

df2['Posicion'].replace({'Goalkeeper':'GK',
                         'Left Winger':'EI',
                         'N':'',
                         'None':'',
                         'Sweeper':'DFC'}, 
                        regex=True, 
                        inplace=True)

Output:

     Posicion
0        1.GK
1  2.Midfield
2        3.EI
  • Related