Home > Back-end >  How to return numerical part of a string before underscore
How to return numerical part of a string before underscore

Time:07-21

CC3309_EasdfewrfwerwxD2Svddserw10_2022 

For the above string, how can I return 3309 when doing a str.replace in the dataframe cell in pandas. I used this:

df['col_name'].str.replace(r'^CC([0-9]{2,})_', r'val_to_be_replaced with', regex = True)

The output should have 3309 in the col_name

CodePudding user response:

Instead of str.replace you could use str.extract like this:

df['col_name'] = df['col_name'].str.extract(r'^CC(\d )_')

CodePudding user response:

string = 'CC3309_EasdfewrfwerwxD2Svddserw10_2022'
split = string.split('_')
print(split[0].replace('C',''))
  • Related