【问题标题】:Not able to replace the string containing $ in pandas column无法替换熊猫列中包含 $ 的字符串
【发布时间】:2019-03-04 10:14:45
【问题描述】:

我有一个dataframe

df = pd.DataFrame({'a':[1,2,3], 'b':[5, '12$sell', '1$sell']})

我想替换 b 列中的 $sell

所以我尝试了replace() 方法,如下所示

df['b'] = df['b'].str.replace("$sell","")

但它不会替换给定的字符串,它给了我与原始相同的数据帧。

当我将它与apply 一起使用时它正在工作

df['b'] = df['b'].apply(lambda x: str(x).replace("$sell",""))

所以我想知道为什么它在以前的情况下不起作用?

注意:我尝试只替换 $ 并且令人震惊的是它的工作原理。

【问题讨论】:

  • 您在发帖之前阅读过the documentation 吗?你从中学到了什么?为什么它没有回答你的问题?

标签: python string pandas series


【解决方案1】:

是正则元字符(字符串结尾),转义或者加参数regex=False:

df['b'] = df['b'].str.replace("\$sell","")
print (df)
   a    b
0  1  NaN
1  2   12
2  3    1

df['b'] = df['b'].str.replace("$sell","", regex=False)

如果还需要值 5,什么是数字,请使用 Series.replace 和 regex=True 来替换子字符串 - 不涉及数字值:

df['b'] = df['b'].replace("\$sell","", regex=True)

print (df['b'].apply(type))
0    <class 'int'>
1    <class 'str'>
2    <class 'str'>
Name: b, dtype: object

或将列的所有数据转换为字符串:

df['b'] = df['b'].astype(str).str.replace("$sell","", regex=False)

print (df['b'].apply(type))
0    <class 'str'>
1    <class 'str'>
2    <class 'str'>
Name: b, dtype: object

如果没有可能的缺失值,为了获得更好的性能,请使用列表理解:

df['b'] = [str(x).replace("$sell","") for x in  df['b']]

print (df)
   a   b
0  1   5
1  2  12
2  3   1

【讨论】:

  • 您需要转义反斜杠或使用原始字符串。
【解决方案2】:
df['b'] = df['b'].str.replace("$sell","", regex=False)

【讨论】:

    【解决方案3】:

    $ 是一个正则表达式特殊字符。默认情况下,pd.Series.str.replace 使用 regex=True

    改为指定regex=False

    df['b'] = df['b'].str.replace('$sell', '', regex=False)
    

    【讨论】:

      【解决方案4】:

      str.replace 假定正在使用正则表达式。所以你需要使用转义,即

      df['b'] = df['b'].str.replace("\$sell","")
      

      【讨论】:

        猜你喜欢
        • 2019-11-23
        • 2018-12-05
        • 2019-06-03
        • 2017-02-07
        • 2017-03-12
        • 2018-08-08
        • 2019-02-06
        • 2018-11-11
        • 2021-05-15
        相关资源
        最近更新 更多