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(假)。
解决方案
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
需要三个参数:一种正则表达式模式,可找到一些零到任意长度的空格,后跟一个数字。请注意,找到的数字不包含在拆分分隔符中。
# The (?=\d) is a look ahead search pattern '\s*(?=\d)'
第二个参数
1
指定要执行多少拆分- 第三个参数指出这个结果应该被分成一个数据框
推荐阅读
- c++ - GPEdit.h 未编译
- android - 如何使用 Anko doAsync 处理 UI 线程上的 Kotlin-Room 异常
- flutter - Flutter,Dismissible中如何使用confirmDismiss?
- php - 如何在现有的 echo 中回显 iframe
- plsql - 在预期以下情况之一时遇到符号“文件结尾”
- javascript - 如何复制节点/电子中的图像文件并能够将其作为文件粘贴到 Windows 中的另一个目录?
- mysql - 如何根据类别从数据库中选择不同的数据
- php - PHP服务器的Angular 7 POST方法不起作用
- python - 在python中插入模块
- c# - 当我向项目添加新迁移时,EF Core 2 仍然运行 Initial 而不是最后一次迁移