在“熊猫”列中拆分字符串和数字

时间:2019-08-07 05:30:13

标签: python pandas

我是python的初学者。我有一个dataframe看起来像这样:

df
No  ID
1   52Device-24-03HAntang
2   40Device-16HAntang

我想拆分ID列。我的预期结果如下:

Result
No  ID                      No_ID   Device        Code  Name
1   52Device-24-03HAntang   52      Device-24-03  H     Antang
2   40Device-16HAntang      40      Device-16     H     Antang

谢谢

1 个答案:

答案 0 :(得分:2)

如果需要用大写字母分隔,请先在Series.str.replace前面加上空格,然后再用Series.str.split将此空格分隔:

cols = ['No_ID','Device','Code','Name']
df[cols] = df['ID'].str.replace(r"([A-Z])", r" \1").str.split(expand=True)
print (df)
   No                     ID No_ID        Device Code    Name
0   1  52Device-24-03HAntang    52  Device-24-03    H  Antang
1   2     40Device-16HAntang    40     Device-16    H  Antang