首页 > 解决方案 > Str 仅在特定位置拆分

问题描述

嗨,我怎么能在一个数字后分割一个点并只为原始 df 生成两列?

df.name
 ``         
0    1. The start
1    2. Today's world
2    3. Today's world vs. yesterday.
...
20   20. The change

预期输出:

     number   title
0     1       The start
1     2       Today's world
2     3       Today's world vs. yesterday.
...
20    20      The change

我试过了

df[['number', 'title']] = df.name.str.split('(\d+.)', expand=True)

标签: pythonpython-3.xpandasstringsplit

解决方案


用于Series.str.extract除以之前的整数.和其他值:

df[['number', 'title']] = df.name.str.extract('(^\d+)\.\s+(.*)')

print (df)
                               name number                          title
0                      1. The start      1                      The start
1                  2. Today's world      2                  Today's world
2   3. Today's world vs. yesterday.      3   Today's world vs. yesterday.
20                   20. The change     20                     The change

推荐阅读