首页 > 解决方案 > 获取 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(假)。

标签: python-3.xpandas

解决方案


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. 第三个参数指出这个结果应该被分成一个数据框

推荐阅读