1

I have a column containing values. I want to split it based on a regex. If the regex matches, the original value will be replaced with the left-side of the split. A new column will contain the right-side of a split.

Below is some sample code. I feel I am close but it isn't quite working.

import pandas as pd
import re

df = pd.DataFrame({ 'A' : ["test123","foo"]})

// Regex example to split it if it ends in numbers
r = r"^(.+?)(\d*)$"

df['A'], df['B'] = zip(*df['A'].apply(lambda x: x.split(r, 1)))
print(df)

In the example above I would expect the following output

         A        B
0     test      123
1     foo

I am fairly new to Python and assumed this would be the way to go. However, it appears that I haven't quite hit the mark. Is anyone able to help me correct this example?

3 Answers 3

3

Just base on your own regex

df.A.str.split(r,expand=True).replace('',np.nan).dropna(thresh=1,axis=1).fillna('')
Out[158]: 
      1    2
0  test  123
1   foo     


df[['A','B']]=df.A.str.split(r,expand=True).replace('',np.nan).dropna(thresh=1,axis=1).fillna('')
df
Out[160]: 
      A    B
0  test  123
1   foo     
Sign up to request clarification or add additional context in comments.

2 Comments

Maybe I'm missing something but how do I add this to column A and column B? I see the example output you provided is column 1 and 2. If I do df['A'], df['B'] = yourCode I get values of 1 and 2 instead of what's expected
@ekjcfn3902039 updated ...You just need to assign it back
2

Your regex is working just fine, use it with str.extract

df = pd.DataFrame({ 'A' : ["test123","foo", "12test3"]})
df[['A', 'B']] = df['A'].str.extract("^(.+?)(\d*)$", expand = True)


    A       B
0   test    123
1   foo 
2   12test  3

Comments

0
def bar(x):
    els = re.findall(r'^(.+?)(\d*)$', x)[0]
    if len(els):
        return els
    else:
        return x, None


def foo():
    df = pd.DataFrame({'A': ["test123", "foo"]})
    df['A'], df['B'] = zip(*df['A'].apply(bar))
    print(df)

result:

      A    B
0  test  123
1   foo   

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.