我有一个df列,其中包含
Phone number
12399422/930201021
5451354;546325642
789888744,656313214
123456654
我想将其分为两列
Phone number1 Phone number2
12399422 930201021
5451354 546325642
789888744 656313214
123456654
我尝试使用Apply
df['TELEPHONE1'] = df['TELEPHONE'].str.split(',').str.get(0)
df['TELEPHONE2'] = df['TELEPHONE'].str.split(',').str.get(1)
df['TELEPHONE1'] = df['TELEPHONE'].str.split(';').str.get(0)
df['TELEPHONE2'] = df['TELEPHONE'].str.split(';').str.get(1)
df['TELEPHONE1'] = df['TELEPHONE'].str.split('/').str.get(0)
df['TELEPHONE2'] = df['TELEPHONE'].str.split('/').str.get(1)
但是它只能分割'/'谢谢您的帮助
答案 0 :(得分:3)
使用str.split
df.Phonenumber.str.split('/|;|,',expand=True).add_prefix('Number_')
Number_0 Number_1
0 12399422 930201021
1 5451354 546325642
2 789888744 656313214
3 123456654 None
答案 1 :(得分:1)
只需在\D
(非数字)上分割即可:
(df['Phone number'].str.split(r'\D', expand=True)
.rename(columns=lambda x: f'num{x+1}'))
num1 num2
0 12399422 930201021
1 5451354 546325642
2 789888744 656313214
3 123456654 None
...假设电话号码仅包含数字。
或者,使用extractall
并仅匹配数字:
df['Phone number'].str.extractall(r'(\d+)')[0].unstack()
match 0 1
0 12399422 930201021
1 5451354 546325642
2 789888744 656313214
3 123456654 NaN