获取熊猫中字符串中第一次出现整数的索引

时间:2019-05-10 13:57:35

标签: python-3.x pandas

我想问一下使用Pandas在字符串中查找整数首次出现的索引的最佳方法是什么。

我有这个示例代码,

df["column"] = "sample code is 1234 just like that 6789"

我的目标是能够将“示例代码为”和“ 1234就像6789一样”分开。为此,我必须确定在哪里分隔字符串,即寻找整数的首次出现。

我希望得到这个结果,

df["column1"] = sample code is
df["column2"] = 1234 just like that 6789

我使用了这段代码,

df["column"].str.find(r'[0-9]'))

但是,它返回-1(否)。

1 个答案:

答案 0 :(得分:0)

split

df[['column1', 'column2']] = df.column.str.split('\s*(?=\d)', 1, expand=True)

df

                                    column         column1                   column2
0  sample code is 1234 just like that 6789  sample code is  1234 just like that 6789

详细信息

  • df.column.str.split需要三个参数:

    1. 一个正则表达式模式,它找到一些零到任意长度的空格,后跟一个数字。请注意,找到的数字未包含在分隔符中。

      # The (?=\d) is a look ahead search pattern
      '\s*(?=\d)'
      
    2. 第二个参数1指定要执行的拆分次数

    3. 第三个参数指出应将此结果拆分为一个数据框