Replace part of string in column DataFrame

Question:

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)
Asked By: Carlos Lozano

||

Answers:

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
Answered By: Rabinzel
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.