首先对不需要的数据进行切片,然后使用split
(假设数据长度 Ph 不变):
df[['Contact1','Contact2']] = df.Contact.str[:-8].str.split('[-]',expand=True)
如果 Ph 之后的数据不是经常用于extract
字母和空格:
df[['Contact1','Contact2']] = df.Contact.str.split('[-]',expand=True)
df['Contact2'] = df.Contact2.str.extract('([a-zA-Z ]+)')[0].str.rstrip()
df = pd.DataFrame({'Name':['John','David'],
'Occupation':['CEO','Dep Dir'],
'Contact':['HP No-Mobile Ph 123:456','Off-Mobile Ph']},)
print(df)
Name Occupation Contact
0 John CEO HP No-Mobile Ph 123:456
1 David Dep Dir Off-Mobile Ph
df[['Contact1','Contact2']] = df.Contact.str.split('[-]',expand=True)
print(df)
Name Occupation Contact Contact1 Contact2
0 John CEO HP No-Mobile Ph 123:456 HP No Mobile Ph 123:456
1 David Dep Dir Off-Mobile Ph Off Mobile Ph
df['Contact2'] = df.Contact2.str.extract('([a-zA-Z ]+)')[0].str.rstrip()
print(df)
Name Occupation Contact Contact1 Contact2
0 John CEO HP No-Mobile Ph 123:456 HP No Mobile Ph
1 David Dep Dir Off-Mobile Ph Off Mobile Ph