【问题标题】:how to replace 2 double quotes into single in dataframe?如何在数据框中将 2 个双引号替换为单引号?
【发布时间】:2020-10-30 08:49:45
【问题描述】:

我正在尝试将两个双引号替换为单引号。你能帮帮我吗?

例子:

""My name is shivam.""

预期输出:

"My name is shivam."

我认为在将此数据帧保存到 csv 文件时出现问题。数据框是正确的。

【问题讨论】:

  • 明确一点,如果我将该字符串放入一个变量中,它会是:'""My name is shivam.""',而您希望它变成'"My name is shivam."'
  • 请提供有关该问题的更多上下文。该字符串出现在哪里?一个文件?
  • 是的,它是一列值。这个东西是大多数列。
  • df.replace({'\""': '"'}, regex=True)

标签: python python-3.x regex pandas dataframe


【解决方案1】:

对于所有列,只需运行:

df = df.apply(lambda s:s.replace('(")(")','"', regex=True))

【讨论】:

  • 不错的解决方案,只是提醒一下,就地会贬值。 link
  • 请检查一下。谢谢。
【解决方案2】:

IIUC,您可以尝试将捕获组替换为其第一个实例。

print(s)

0     ""My name is shivam.""  
1                       Shivan
2                     "Shivan"

s1 = s.replace('(")(")',r'\1',regex=True)

print(s1)

0     "My name is shivam."  
1                     Shivan
2                   "Shivan"

【讨论】:

    【解决方案3】:

    试一试

    df[column_name].replace('""','"',regex=True)
    

    对于多列

    df.replace('""','"',regex=True)
    

    【讨论】:

    • 它出现在大多数列中。
    • 不在单列中'。
    • 然后直接使用df.replace()
    • 但在保存到文件时,它再次出现在 2 个双引号中。
    • 您是否正在使用新生成的数据框对象更新数据框对象,如下所示?或不? df = df.replace('""','"',regex=True) 或 df.replace('""','"',regex=True, inplace = True)
    【解决方案4】:

    也许你可以使用替换方法。

    string = '""My name is shivam.""'
    string = string.replace('""','"')
    print(string)
    

    如果它在列中,请尝试

    df['column'] = df['column'].str.replace('""','"')
    

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 2018-11-18
      • 1970-01-01
      • 2017-12-29
      • 2017-06-19
      • 2015-08-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      相关资源
      最近更新 更多