【问题标题】:Replace not working for multiple strings replacement when each row is a list当每行是一个列表时,替换不适用于多个字符串替换
【发布时间】:2020-06-27 10:41:52
【问题描述】:

我正在尝试从我的数据框中构建一个替换 httphttpscomwww 的函数。

df

content                                                       Col2  Col3   Col4
[www,roger, that,com, http, great, hi, www]                   89     78     40
[http, https,www,roger, http, for,com, http, you, bye, www]   93     94     30
and so one...there are 30,000 rows 

并不是每一行都是我的数据集中列内容的列表

定义函数

def replace(df):
    for row in df:
        for index, item in enumerate(row):
            # create string *and update row*
            row[index] = item.replace("www", " ")
            row[index] = item.replace("http", " ")
            row[index] = item.replace("https", " ")
            row[index] = item.replace("com", " ")
    return df

调用函数

df['content']=replace(df['content'])

问题是 www 被替换了,但是 http、https 和 com 没有被替换。我做错了什么

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以对列做一个简单的列表推导:

    rep = ['http', 'https', 'www', 'com']
    df['col2'] = df['col1'].apply(lambda x: [i for i in x if i not in rep])
    
                                                col1                      col2
    0  [www, roger, that, com, http, great, hi, www]  [roger, that, great, hi]
    1                 [http, https, www, roger, for]              [roger, for]
    

    样本数据

    cl=[["www","roger", "that","com", "http", "great", "hi", "www"],
        ["http", "https", "www","roger","for"]]
    
    df = pd.DataFrame({'col1': cl})
    

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 1970-01-01
      • 2018-01-14
      • 2021-10-08
      • 2020-08-31
      • 2017-10-23
      • 1970-01-01
      • 2011-07-01
      相关资源
      最近更新 更多