首页 > 解决方案 > 如何在 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)    

标签: pythonpandas

解决方案


使用带有负面后视的捕获组:

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


推荐阅读