简体   繁体   中英

Replace part of string in column DataFrame

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM