python - 更改熊猫列中的数字字符串
问题描述
背景
我有一个包含 0,1 或 >1df
的列的示例Text
ABC
import pandas as pd
df = pd.DataFrame({'Text' : ['Jon J Mmith ABC: 1111111 is this here',
'ABC: 1234567 Mary Lisa Rider found here',
'Jane A Doe is also here',
'ABC: 2222222 Tom T Tucker is here ABC: 2222222 too'],
'P_ID': [1,2,3,4],
'N_ID' : ['A1', 'A2', 'A3', 'A4']
})
#rearrange columns
df = df[['Text','N_ID', 'P_ID']]
df
Text N_ID P_ID
0 Jon J Mmith ABC: 1111111 is this here A1 1
1 ABC: 1234567 Mary Lisa Rider found here A2 2
2 Jane A Doe is also here A3 3
3 ABC: 2222222 Tom T Tucker is here ABC: 2222222... A4 4
目标
1)将列(例如)中的ABC
数字更改为Text
ABC: 1111111
ABC: **BLOCK**
2)创建一个Text_ABC
包含此输出的新列
期望的输出
Text N_ID P_ID Text_ABC
0 Jon J Mmith ABC: 1111111 is this here A1 1 Jon J Mmith ABC: **BLOCK** is this here
1 ABC: 1234567 Mary Lisa Rider found here A2 2 ABC: **BLOCK** Mary Lisa Hider found here
2 Jane A Doe is also here A3 3 Jane A Doe is also here
3 ABC: 2222222 Tom T Tucker is here ABC: 2222222 A4 4 ABC: **BLOCK** Tom T Tucker is here ABC: **BLOCK**
问题
如何实现我想要的输出?
解决方案
如果要替换所有数字,您可以执行以下操作:
df['Text_ABC'] = df['Text'].replace(r'\d+', '***BLOCK***', regex=True)
但是,如果您想更具体并且只替换 之后的数字ABC:
,那么您可以使用以下命令:
df['Text_ABC'] = df['Text'].replace(r'ABC: \d+', 'ABC: ***BLOCK***', regex=True)
给你:
df
Text P_ID N_ID Text_ABC
0 Jon J Smith ABC: 1111111 is this here 1 A1 Jon J Smith ABC: ***BLOCK*** is this here
1 ABC: 1234567 Mary Lisa Rider found here 2 A2 ABC: ***BLOCK*** Mary Lisa Rider found here
2 Jane A Doe is also here 3 A3 Jane A Doe is also here
3 ABC: 2222222 Tom T Tucker is here ABC: 2222222... 4 A4 ABC: ***BLOCK*** Tom T Tucker is here ABC: ***BLOCK...
作为一个正则表达式,\d+
意思是“匹配一个或多个连续数字”,因此使用它表示“用”replace
替换一个或多个连续数字***BLOCK***
推荐阅读
- r - 具有两个循环和存储结果的 R 并行编程
- java - 在 wso2 EI 中为多个 salesforce 操作建立单个 salesforce 连接
- laravel - SQLSTATE [23000]:违反完整性约束:1048 列“restaurant_id”不能为空
- azure - azure python sdk方法中的custom_headers是什么?
- java - 从所有 Cucumber 功能和场景中获取测试树?
- python-3.x - 在 Python/Kivy 中更改设备壁纸
- python - 如何使用 django allauth 在电子邮件中添加图像
- java - 如何使用 Selenium webdriver java 使用 DOM 定位器来定位 Web 元素
- node.js - AWS Lambda + 自定义授权方 + JWT + 黑名单令牌
- vhdl - VHDL正确停用组件