python - 如何在 for 循环中使用占位符?
问题描述
我有以下代码:
df['Variable Name']=df['Variable Name'].replace(' 15 °',' at 15 °', regex=True)
df['Variable Name']=df['Variable Name'].replace(' at at 15 °',' at 15 °', regex=True)
df['Variable Name']=df['Variable Name'].replace(' 0 °',' at 0 °', regex=True)
df['Variable Name']=df['Variable Name'].replace(' at at 0 °',' at 0 °', regex=True)
df['Variable Name']=df['Variable Name'].replace(' 5 °',' at 5 °', regex=True)
df['Variable Name']=df['Variable Name'].replace(' at at 5 °',' at 5 °', regex=True)
并想知道如何缩短它。我尝试了一个 for 循环:
for x in range(0,15,5):
df['Variable Name']=df['Variable Name'].replace(' %s °',' at %s °', x, regex=True)
df['Variable Name']=df['Variable Name'].replace(' at at %s °',' at %s °', x, regex=True)
但我收到错误消息:
ValueError: For argument "inplace" expected type bool, received type int.
有什么更好的方法呢?
编辑:添加片段
Variable Name Condition
Density 15 °C (g/mL)
Density 0 °C (g/mL)
Density 5 °C (g/mL)
Calculated API Gravity
Viscosity at 15 °C (mPa.s)
Viscosity at 0 °C (mPa.s)
Viscosity at 5 °C (mPa.s)
Surface tension 15 °C (oil - air)
Interfacial tension 15 °C (oil - water)
解决方案
使用带有负面后视的捕获组:
import pandas as pd
s = pd.Series([' 15 °', ' at 15 °', ' 0 °', ' at 0 °', ' 5 °', ' at 5 °'])
s = s.str.replace('(?<!at)\s+(15|0|5) °', r' at \1 °', regex=True)
print(s)
输出
0 at 15 °
1 at 15 °
2 at 0 °
3 at 0 °
4 at 5 °
5 at 5 °
dtype: object
正如regex=True
指示我们将使用正则表达式替换的那样,该模式(?<!at)\s+(15|0|5) °
意味着匹配前面没有at
(作为前一个单词)的 15、0 或 5。这种表示法(?<!at)
被称为负向回溯,类似于查看前面的字符,看看它们是否不匹配,在这种情况下at
。这(15|0|5)
是一个捕获组,每个捕获组都有一个对应的索引,您可以在替换模式中使用它,如“在\1°”中。因此,例如,该模式只会替换15
前面没有 at 的 a,by at 15
。
推荐阅读
- phpmyadmin - 突然,phpmyadmin 不起作用,我真的不明白为什么 - 日志对我来说看起来不错
- python-3.x - 获取vimeo账号的所有公共视频ID列表
- python - FFMPEG Python:遇到具有相同上游标签的多个传出边缘的比例(1920、1080)无;可能需要一个`split`过滤器
- excel - 我 trq 将 API_MENU 从 32 位转换为 64 位,但“类型不匹配”
- faker - 在没有特定值的情况下调用 Faker
- cucumber - 如何向 Cucumber 报告添加选项以删除具有特定标签的场景
- linux-kernel - 为什么进程限制与 Linux 内核中的信号相关联?
- java - 自应用签名以来,文档已被更改或损坏 itext 5.5.11
- html - 如何使用引导程序水平对齐多个项目?
- sql-server - Windows 更新导致 SSMS 与我的服务器的连接出现问题