Home > Software design >  Extract substring from a string using Python regex
Extract substring from a string using Python regex

Time:03-20

I am working with data frames. One of my column look like this

                   X
4028    Toolx-2022-01-18_15-26-09.blf.26
4029    Temperaturelow-2022-01-18_15-26-09.blf.27
4031    Temperaturehigh2022-01-18_15-26-09.blf.28
4032    low2022-01-18_15-26-09.blf.29
4032    high2022-01-18_15-26-09.blf.30
Name: X, dtype: object

I want my output like this

                  X
4028    2022-01-18 15-26-09 26
4029    2022-01-18 15-26-09 27
4030    2022-01-18 15-26-09 28
4031    2022-01-18 15-26-09 29
4032    2022-01-18 15-26-09 30
Name: X, dtype: object 

Can anyone please help me how to do this in Python ?

CodePudding user response:

We can use str.extract here:

df["X"] = df["X"].str.extract(r'(\d{4}-\d{1,2}-\d{1,2})_(\d{2}-\d{2}-\d{2}).*\.(\d )', r'\1 \2 \3')

Here is a regex demo.

  • Related