简体   繁体   中英

pandas split column text into multiple columns

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

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
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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM