python - extract number from string in pandas dataframe column
问题描述
I have a dataframe in the below format and and trying to use the extract function but I keep getting the following error:
ValueError: If using all scalar values, you must pass an index
column1 column2
1 abc2150/abc2152/abc2154/abc215601/U215602
df.column2.str
.split('/',expand=True)
.apply(lambda row: row.str.extract('(\d+)', expand=True))
.apply(lambda x: '/'.join(x.dropna().astype(str)), axis=1)
I need the output in the below format.
column1 column2
1 2150/2152/2154/215601/215602
Please let me know how to fix it.
Thanks
解决方案
您可以改为使用str.replace
积极的前瞻来删除数字部分之前的所有字符:
df.column2.str.replace(r'[a-zA-Z]+(?=\d+)','')
0 2150/2152/2154/215601/215602
Name: column2, dtype: object
推荐阅读
- arduino - Arduino将代码上传到esp8266 nodemcu时出错
- azure-data-lake - Visual Studio 表格模型到数据湖
- r - Quantmod 一个pdf中的多个图表
- javascript - 如何从 URL 获取文件元数据
- javascript - 将 JSON 文件从数据库解析为 JavaScript 的问题
- google-cloud-platform - 您可以通过 GDM 将更改传播到多个项目吗?
- python - 浮动表示的差异
- sql - 将 Count 与 Case 表达式一起使用
- r - 休息之间的空间均匀 - ggplot2
- wordpress - 如何为 wordpress 创建子插件