【问题标题】:Pandas, replace double quotation marks to NaN熊猫,将双引号替换为 NaN
【发布时间】:2022-01-03 11:50:28
【问题描述】:

输入:

"""""""NW_020998607.1"""    397418
"""""""NW_020998607.1"""    2583299
"""""""NW_020998607.1"""    2742463
"""""""NW_020998607.1"""    9131893
"""""""NW_020998607.1"""    11763556
"""""""NW_020998607.1"""    11763572

预期输出:

NW_020998607.1  397418
NW_020998607.1  2583299
NW_020998607.1  2742463
NW_020998607.1  9131893
NW_020998607.1  11763556
NW_020998607.1  11763572

输出:

"""""""NW_020998607.1"""    397418
"""""""NW_020998607.1"""    2583299
"""""""NW_020998607.1"""    2742463
"""""""NW_020998607.1"""    9131893
"""""""NW_020998607.1"""    11763556
"""""""NW_020998607.1"""    11763572

代码:

import pandas as pd

with open(input, 'r') as aaa:
    lines_1 = [line.rstrip('\n').split('\t') for line in aaa]

df = pd.DataFrame(lines_1)

df_replace[0] = df.replace[0]('"', '')

我尝试将 '"' 替换为 '',但 pandas 没有任何反应。 你能帮我去掉双引号吗?

【问题讨论】:

  • 您确定要替换正确的变量吗? str.replace('"', '') 应该可以正常工作。

标签: python pandas replace double multiple-columns


【解决方案1】:

您可以使用pandas.Series.str.strip("\"")

>>> import pandas as pd
>>>
>>> with open("input.txt") as f:
...     df = pd.read_csv(f, sep="\s+", header=None)
...     df[0] = df[0].str.strip("\"")
...     print(df)
...
                0         1
0  NW_020998607.1    397418
1  NW_020998607.1   2583299
2  NW_020998607.1   2742463
3  NW_020998607.1   9131893
4  NW_020998607.1  11763556
5  NW_020998607.1  11763572

注意:您可以使用pd.read_csv直接从文件对象中读取数据,分隔符为\s+

【讨论】:

    【解决方案2】:

    您可以使用字符串替换方法。

    name = '"""""""NW_020998607.1"""    397418'
    
    print(name.replace("\"",""))
    

    输出

    NW_020998607.1 397418

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多