【问题标题】:Pandas removing characters from String熊猫从字符串中删除字符
【发布时间】:2020-04-26 20:13:11
【问题描述】:

我想简化我的 3 行代码,将方括号去掉为一行:

df = pd.DataFrame(dict(words=['[hello]',
                            '[hello,[Name, World, Max]',
                            np.nan, 
                            '[Goodbye]',
                            np.nan,
                            '[hello, [goodbye], hello]']))
df['words'].fillna("N/A", inplace=True)
df['words']=df['words'].str.extract("\[", "")
df['words']=df['words'].str.replace("\]", "")

我尝试了这里提到的几种方法,但都不起作用(替换、扩展):remove characters from pandas column

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为您需要 Series.str.replace 的值在 [] 中:

    df['words'] = df['words'].fillna("N/A").str.replace("[\]\[]", "")
    

    或者将| 用于正则表达式or

    df['words'] = df['words'].fillna("N/A").str.replace("\]|\[", "")
    

    print (df)
                        words
    0                   hello
    1  hello,Name, World, Max
    2                     N/A
    3                 Goodbye
    4                     N/A
    5   hello, goodbye, hello
    

    【讨论】:

    • @user2266957 - 一个想法 - df['words'] = df['words'].fillna("N/A").astype(str).str.replace("[\]\[]", "")
    • 这行得通!您能解释一下为什么需要添加 [ ] 吗?
    • @ohoh7171 - 检查link
    【解决方案2】:
    import numpy as np
    
    df = pd.DataFrame(dict(words=['[hello]',
                                '[hello,[Name, World, Max]',
                                np.nan, 
                                '[Goodbye]',
                                np.nan,
                                '[hello, [goodbye], hello]']))
    df ['words'] = df['words'].fillna("N/A", inplace=False).replace('\[{0,1}\]{0,1}', '', regex=True)
    

    【讨论】:

      猜你喜欢
      • 2016-10-21
      • 2023-01-11
      • 2017-10-01
      • 2021-03-16
      • 2021-09-25
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      相关资源
      最近更新 更多