2

How can I split the column value into 2 new columns:

Data:

WO No
OR-20180422-12345

Input:

df[['CO','WO Date',WO ID']] = df.pop('WO No').str.split('-', expand=True)

Expected output:

 CO     WO Date #as dd/mm/yyyy date format
 OR     22/04/2018

4 Answers 4

2

This is one way using vectorised functionality.

df = pd.DataFrame({'WO No': ['OR-20180422-12345']})

df[['CO', 'WO Date', 'WO ID']] = df['WO No'].str.split('-', expand=True)

df['WO Date'] = pd.to_datetime(df['WO Date']).dt.strftime('%d/%m/%Y')

df = df[['CO', 'WO Date']]

print(df)

#    CO     WO Date
# 0  OR  22/04/2018
Sign up to request clarification or add additional context in comments.

1 Comment

This solution is better, as it avoids apply. Nice.
1
def rule(a):
    vals = a.split("-")
    d = pd.to_datetime(vals[1])
    d = d.strftime('%d/%m/%Y') # your format 
    return pd.Series({"C0": vals[0], "W0 Date": d})

df["W0 No"].apply(rule)

Output

    C0  W0 Date
0   OR  22/04/2018

Comments

1

You can use str.split:

def split_it(s):
    return pd.Series({'CO': s[0], 'WO Date': pd.to_datetime(s[1])})
>>> df['WO no'].str.split('-').apply(split_it)
    CO  WO Date
0   OR  2018-04-22

Comments

0

Setup:

s = pd.Series(data="OR-20180422-12345")    

Use extractall

df = str.extractall("(?P<CO>[A-Z]{2})-(?P<WOdate>\d{8})-\d+").reset_index(drop=True)

Cleanup dtypes:

df['WOdate'] = df['WOdate'].apply(pd.to_datetime);df

Out:

   CO     WOdate
0  OR 2018-04-22

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.