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

时间:2019-10-22 20:01:43

标签: 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)    

4 个答案:

答案 0 :(得分:3)

使用后向否定的捕获组:

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 15而不是at之前的内容。

答案 1 :(得分:0)

不确定为什么要使用RegEx标志,但不需要它。 inplace是第三个参数,需要一个布尔值,但是您将x作为第三个参数,这就是为什么它失败的原因。您没有正确使用%格式。

通过完全巧合,inplace也可以用来简化问题。在这种情况下,您无需重新分配。这是一些不错的代码:

for x in (0, 5, 15): # You were using range() wrong - this is correct
    df['Variable Name'].replace(' %s °' % x,' at %s °' % x, inplace=True)
    df['Variable Name'].replace(' at at %s °' % x,' at %s °' % x, inplace=True)

如果可以使用%和f字符串,请尝试避免使用.format()格式。但这应该可行。

答案 2 :(得分:0)

您可以通过可选的捕获组将自己保存在replace

s = pd.Series(['that at 15 °', 'this 15 °', 
               'that at 5 °', 'this 5 °', 
               'that at 0 °', 'this 0 °'])

for x in [0, 5, 15]:
    s = s.str.replace(f'((?: at)? {x} °)', f' at {x} °')

输出:

0    that at 15 °
1    this at 15 °
2     that at 5 °
3     this at 5 °
4     that at 0 °
5     this at 0 °
dtype: object

答案 3 :(得分:0)

与正则表达式 dict单次通过

In [113]: df = pd.DataFrame(columns=['Variable Name'], data=[' 15 °', ' at at 15 °', ' 0 °', ' at at 0 °', '
     ...:  5 °', ' at at 5 °'])                                                                             

In [114]: df['Variable Name'].replace(regex={r'^\s*(\d+) °': r'at \1 °', r'at at (\d+) °': r' at \1 °'})    
Out[114]: 
0      at 15 °
1      at 15 °
2       at 0 °
3       at 0 °
4       at 5 °
5       at 5 °
Name: Variable Name, dtype: object