【问题标题】:How do I remove special character like "," within a string in a DataFrame?如何在 DataFrame 中的字符串中删除特殊字符,例如“,”?
【发布时间】:2021-11-27 09:42:35
【问题描述】:

我有一个如下类型的数据框:pandas.core.frame.DataFrame

newdf = pd.DataFrame([
    [0, "Hello, How are you?", 1],
    ["I wish, we could get it right", 0, 0],
    [0, "Hey there, hope you are doing well", 0]],
    columns=['Mon','Tue','Wed'])



newdf

|Mon                            |   Tue                              |  Wed |
|:------------------------------|:----------------------------------:|-----:| 
| 0                             |   Hello, How are you?              |  1   |
|I wish, we could get it right  | 0                                  |  0   |
|              0                |Hey there, hope you are doing well  |  0   |

我想把它保存为CSV并上传到MySQL,但是句子中有“,”的字符串

我想用“”或“-”替换所有“,”

我试过了

newdf1 = newdf.replace(",","-")

数据框没有变化

请帮助替换 DataFrame 中字符串中的字符。

我之前使用.replace() 来更改单元格的整个元素并且它有效,但现在我想读取字符串内部并执行操作。

【问题讨论】:

    标签: python pandas string dataframe replace


    【解决方案1】:

    您必须首先启用正则表达式以进行子字符串匹配:

    >>> newdf.replace(",", "-", regex=True)
                                 Mon                                 Tue  Wed
    0                              0                 Hello- How are you?    1
    1  I wish- we could get it right                                   0    0
    2                              0  Hey there- hope you are doing well    0
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2021-02-17
      • 2015-11-11
      • 2012-05-30
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多