【问题标题】:Remove strings at column based on strings of another column根据另一列的字符串删除列中的字符串
【发布时间】:2019-06-20 12:19:32
【问题描述】:

我在pandaspython 有这个:

    text1       text2
0   sunny       This is a sunny day
1   rainy day   No this day is a rainy day

我想把它改成这样:

    text1       text2
0   sunny       This is a day
1   rainy day   No this day is a

因此,我想根据同一行的text1text2 中删除一些文本。

我这样做了:

df = df.apply(lambda x: x['text2'].str.replace(x['text1'], ''))

但我遇到了一个错误:

AttributeError: ("'str' object has no attribute 'str'", 'occurred at index 0')

这可能与此有关: https://stackoverflow.com/a/53986135/9024698.

什么是做我想做的最有效的方法?

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    快速有点丑陋的解决方案是replace - 但如果需要将每行替换为另一列,则可能有多个空格:

    df['text2'] = df.apply(lambda x: x['text2'].replace(x['text1'], ''), axis=1)
    print (df)
           text1              text2
    0      sunny     This is a  day
    1  rainy day  No this day is a 
    

    拆分两列的解决方案:

    df['text2'] = df.apply(lambda x: ' '.join(y for y in x['text2'].split() 
                                              if y not in set(x['text1'].split())), axis=1)
    

    如果需要替换为另一列的所有值,最好使用@Erfan 的解决方案:

    df['text2'].str.replace('|'.join(df['text1']), '') 
    

    【讨论】:

    • 谢谢(点赞)。顺便说一句,我正在寻找 No this day is a,这不是您在第二个解决方案中所拥有的。
    • 你不能简单地使用df['text2'].str.replace('|'.join(df['text1']), '')吗?
    • @Erfan,我不想用另一列的所有值替换
    • 我明白了,那是有道理的 :) @PoeteMaudit
    【解决方案2】:

    这是因为您将函数应用于列而不是行。此外,x['text2'] 已经是一个字符串,因此无需调用.str。通过这些修改,您将拥有:

    print(df.apply(lambda x: x['text2'].replace(x['text1'], ''), axis=1))
    # 0       This is a  day
    # 1    No this day is a
    

    如您所见,您只返回text2

    这是一个返回处理后的整个数据帧的示例:

    # Import module
    import pandas as pd
    
    df = pd.DataFrame({"text1": ["sunny", "rainy day"],
                       "text2": ["This is a sunny day", "No this day is a rainy day"]})
    print(df)
    #        text1                       text2
    # 0      sunny         This is a sunny day
    # 1  rainy day  No this day is a rainy day
    
    # Function to apply
    def remove_word(row):
        row['text2'] = row.text2.replace(row['text1'], '')
        return row
    
    # Apply the function on each row (axis = 1)
    df = df.apply(remove_word, axis=1)
    print(df)
    #        text1              text2
    # 0      sunny     This is a  day
    # 1  rainy day  No this day is a
    

    【讨论】:

      【解决方案3】:

      只需使用replace 方法:

      df["text2"]=df["text2"].replace(to_replace=df["text1"],value="",regex=True)
      

      编辑

      正如@jezrael 所提到的,此方法不考虑周围的空格(因为它们不被正则表达式匹配)。 但是,您可以调整正则表达式以避免其中一些向模式添加可选空格,例如:

      df["text2"]=df["text2"].replace(to_replace=df["text1"]+" *",value="",regex=True)
      

      【讨论】:

        猜你喜欢
        • 2019-07-20
        • 1970-01-01
        • 2023-04-09
        • 2016-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2022-01-01
        相关资源
        最近更新 更多