首页 > 解决方案 > 在 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

谢谢你

标签: pythonpandas

解决方案


如果需要用大写字母分割,首先在大写之前添加空格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

推荐阅读