【问题标题】:Replace or Remove special characters such as ' and " in pandas dataframe替换或删除熊猫数据框中的特殊字符,例如“和”
【发布时间】:2022-07-22 23:32:27
【问题描述】:

在我正在处理的数据框中,有几列包含特殊字符,例如 " 和 ' 。 它们位于列名的末尾或开头。

我怎样才能摆脱它们? 有没有机会读取这些字符的文件?

我尝试了几个选项,但是都不起作用。

列示例如下:

est_soilty_Gh''

upd_siffer_Kh'g

est_soilty_M'''

提前感谢您的帮助!

【问题讨论】:

  • 那些不是特殊字符。您可以使用 str.replacestr.strip("'") 替换它们

标签: python pandas special-characters


【解决方案1】:

另一种选择:

df = pd.DataFrame({"est_soilty_Gh''": [1,2,4],
                    "upd_siffer_Kh'g": [0,0.2,0.5],
                    "est_soilty_M'''": [2,3,4]})



    est_soilty_Gh''  upd_siffer_Kh'g  est_soilty_M'''
0                1              0.0                2
1                2              0.2                3
2                4              0.5                4
df.columns = df.columns.str.replace(r"'", '')


print(df)

est_soilty_Gh  upd_siffer_Khg  est_soilty_M
0              1             0.0             2
1              2             0.2             3
2              4             0.5             4

【讨论】:

    【解决方案2】:

    这样的?

    df.column_name = df.column_name.str.replace(r'["\']', '')
    

    编辑:

    使用正则表达式,感谢@mozway

    【讨论】:

    • 不要替换两次,使用正则表达式r'["\']'
    • 谢谢。我越来越好,至少那次我没有使用列表理解。
    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2021-03-29
    • 2021-08-09
    • 2022-12-07
    • 2020-05-13
    • 1970-01-01
    相关资源
    最近更新 更多