python - 如何使用 re 库或 Excel 工作表中的任何其他方法将字符串拆分为文本和数字?
问题描述
我需要将 Excel 工作表的第一列转换为整数值。需要删除字符串(例如LP001005
,删除LP
并获取剩余的数字)。
我能够在单个变量上实现这一点。但是,我需要在 Excel 表上实现这一点。我的意思是将整个 Excel 转换为 pandas 中的数据框,然后提取Loan_ID
并进行转换(从 中删除LP
)LP001005
,然后使用数据框。
>>> import re
>>> test_str = "Geeks4321"
>>> print("The original string is : " + str(test_str))
The original string is : Geeks4321
>>> res = [re.findall(r'(\d+)', test_str)[0] ]
>>> print("The tuple after the split of string and number : " + str(res))
The tuple after the split of string and number : ['4321']
>>>
Excel 工作表如下所示:
LoanID Name
LP1401 Shubhra
LP1102 Ankit
LP1203 Sowmya
解决方案
您可以使用该.extract()
方法提取 Loan ID 的数字部分:
df = pd.DataFrame({'LoanID': 'LP1401 LP2102 LP3203'.split(),
'Name': 'Shubhra Ankit Sowmya'.split()})
df['LoanID'] = df['LoanID'].str.extract( r'\w(\d+)', expand=False ).astype(int)
print(df)
LoanID Name
0 1401 Shubhra
1 2102 Ankit
2 3203 Sowmya
推荐阅读
- python - 在没有 Redis 的情况下使用 celery 4
- angular - Plotly.js 不适用于 SSR Angular 应用程序
- reactjs - 如何将我的 Reactjs Web 应用程序连接到安全的 MQTT 代理?
- reporting-services - 如何显示该日期没有值的日期
- java - 如何从文件中读取然后倒退?
- gurobi - 如何解决 gurobi 求解器中的导入错误
- python - 为什么这个类中的函数不使用更新的类属性?
- python - Numpy数组:不选择特定的行或列
- android - 如何使用改造 android 捕获图像和发布数据
- mysql - mysql查询不适用于条件