Skip to content Skip to sidebar Skip to footer

Replace Specific Values Inside A Cell Without Chaging Other Values In A Dataframe

I am using pandas and have the following dataframe (df) with a column (mycol1). mycol1 ----------------- |ABC | |CDE | |EFG | |3

Solution 1:

I think you need replace by dictionary with numbers as strings with codes, for replace substrings add regex=True:

d = {'1':'a', '2':'b', '3':'c', '4':'d', '7':'e'}
df['mycol2'] = df['mycol1'].replace(d, regex=True)
print (df)
          mycol1        mycol2
0            ABC           ABC
1            CDE           CDE
2            EFG           EFG
3         2, GHI        b, GHI
4            IJK           IJK
5        2,4 KLM       b,d KLM
6            MNO           MNO
7   1, 2, 3, OPQ  a, b, c, OPQ
8          7 QRS         e QRS
9            STU           STU
10           UWX           UWX
11           XYZ           XYZ

Post a Comment for "Replace Specific Values Inside A Cell Without Chaging Other Values In A Dataframe"