python - 如何在for循环中使用占位符?

标签 python pandas

我有以下代码:

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)是一个捕获组,每个捕获组都有一个相应的索引,您可以在替换模式中使用该索引,如 ' at\1 °' 中。例如,该模式只会替换 15前面没有 at、at 15 .

关于python - 如何在for循环中使用占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58511511/

相关文章:

python - 穿越楼梯的不同方式

python - 为什么要扩展 python 列表

Python pandas 带 to_csv 的大 float

python - 读取带有页脚和末尾任意数量的空白行的 csv 时出现问题

python - 具有大数据集的 Python 中的心烦图

python - 带参数的 Windows 子进程

python - Tkinter 菜单栏插入位置 0 不起作用

python - 如何在 Python 中不带尾随空格进行打印

python : extracting only the first element on a dictionary of list using functions

python - 在传递给 apply() 的自定义函数中访问先前计算的结果