Home > front end >  How to rename value in column?
How to rename value in column?

Time:10-21

I have a dataframe:

  id                 value
4_french:k_15          10
87_nov:k_82            82
11_nov:k_10            10
1_italian:k_11         9

I want to rename values in column id which have nov:k_ giving them new id k so desired result must be:

  id                 value
4_french:k_15          10
k                      82
k                      10
1_italian:k_11         9

How to do that?

CodePudding user response:

you can use .str.replace() and regex like below:

>>> df['id'] = df['id'].str.replace(r'.*nov:k_.*', 'k', regex= True)

>>> df
  id                 value
4_french:k_15          10
k                      82
k                      10
1_italian:k_11         9

CodePudding user response:

Use contains with loc

df.loc[df['id'].str.contains("nov:k_"), 'id'] = "k"

               id  value
0   4_french:k_15     10
1               k     82
2               k     10
3  1_italian:k_11      9

CodePudding user response:

You can also use a simple for loop.

for i in df['id']:
    if "nov:k" in i:
        df = df.replace(i, 'k')
  • Related