0

其中一列是字符串。我想拆分字符串,但它没有用作拆分器的唯一字符。以下是示例数据框:

`df = pd.DataFrame({'Name':['John','David'],'Occupation':['CEO','Dep Dir'],'Contact':['HP No-Mobile Ph 123:456','Off-Mobile Ph 152:256']},`)

我想做的是拆分联系人。我想要的输出如下: 我想要的输出

我使用以下代码在“-”处拆分。

df[['Contact1','Contact2']] = df.Contact.str.split('[-]',expand=True)

但是输出不是我想要的格式。任何人都可以帮助我,这是一个我找不到的具体问题。谢谢,

泽普

4

3 回答 3

1

首先对不需要的数据进行切片,然后使用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
于 2018-10-12T07:03:33.847 回答
1
df[['Contact1','Contact2']] = df['Contact'].str.split('-' or ' ',expand=True)
df.Contact2 = df.Contact2.str.split(' ').str[:-1].apply(' '.join)

出去:

              Contact       Name    Occupation  Contact1    Contact2
0   HP No-Mobile Ph 123:456 John    CEO          HP No     Mobile Ph
1   Off-Mobile Ph 152:256   David   Dep Dir       Off      Mobile Ph
于 2018-10-12T07:05:38.390 回答
1

我相信你需要2 列,然后split是最后一个空格:-rsplit

df[['Contact1','Contact2']] = df.Contact.str.split('-',expand=True)
df['Contact2'] = df['Contact2'].str.rsplit(n=1).str[0]
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 152:256      Off  Mobile Ph
于 2018-10-12T07:07:13.187 回答