6

I have columns with values like this:

Col1

1/1/100 'BA1
1/1/102Packe
1/1/102 'to_

And need to extract just 1/1/100 (from the first row) and so on (1/1/102...)

I am using:

df['col1'] = df['col1'].str.extract('(\d+)/(\d+)/(\d+)', expand=True)

But I'm getting only 1.

Not sure why this is not working, is there a problem with regex or I need some kind of mapping?

3 Answers 3

9

You need to only use a single capturing group:

df['col1'] = df['col1'].str.extract('(\d+/\d+/\d+)', expand=True)
                                     ^           ^

The str.extract method returns the value captured with the first capturing group, and your regex captures the first 1 into that group.

Test:

>>> import pandas as pd
>>> df = pd.DataFrame({"col1":["1/1/100 'BA1", "1/1/102Packe", "1/1/102 'to_"]})
>>> df['col1'].str.extract('(\d+/\d+/\d+)', expand=True)
         0
0  1/1/100
1  1/1/102
2  1/1/102
Sign up to request clarification or add additional context in comments.

Comments

1

you can try this also,

df['Col1']=df['Col1'].str.replace('\d+|/','')

Note: Regex is more powerful than .str.replace.

Comments

1

I suggest this Regex:

df['col1'].str.extract('\b(\d/?)+', expand=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.