python - 如何计算 str.replace 执行的操作数?
问题描述
我有一个带有列注释的数据框,我使用正则表达式来删除数字。我只想计算这种模式改变了多少行。即计算str.replace 操作的行数。
df['Comments']=df['Comments'].str.replace('\d+', '')
输出应该看起来像 -
Operated on 10 rows
解决方案
re.subn() 方法返回执行的替换次数和新字符串。
示例:text.txt 包含以下内容行。
No coments in the line 245
you can make colmments in line 200 and 300
Creating a list of lists with regular expressions in python ...Oct 28, 2018
re.sub on lists - python
示例代码:
count = 0
for line in open('text.txt'):
if (re.subn(r'\d+',"", line)[1]) > 0:
count+=1
print("operated on {} rows".format(count))
对于熊猫:
data['comments'] = pd.DataFrame(open('text.txt', "r"))
count = 0
for line in data['comments']:
if (re.subn(r'\d+',"", line)[1]) > 0:
count+=1
print("operated on {} rows".format(count))
输出:
operated on 3 rows
推荐阅读
- c++ - 如何在 Gtkmm4 中获取 Gtk::Window 的 XId
- sql - 如何使用 oracle 查询找出以下输出
- javascript - 如何在 Map 中找到键,其中键包含某个值?
- java - 使用 Comsol API 在 Java 中出现 FlException:无法获取用户名和密码
- r - 是否可以使用 spData/tmap 包创建英国县的地图
- node.js - Google Translate API:音译输入
- mysql - 如何通过将一个表中的日期与另一个表中最接近和之前的日期匹配来连接两个表
- python - PyOpenCl 简单矩阵乘法
- authentication - JSF 2.3 基于表单的登录和 ViewExpiredException
- sql - 使用 SQL 文件作为 React Native 数据的数据存储库