【问题标题】:re.sub dataframe on pythonpython上的re.sub数据框
【发布时间】:2020-05-24 06:04:31
【问题描述】:

我正在尝试使用 re.sub 正则表达式函数 re.sub url(如 https 或 http) 这是data.csv里面的数据:

    username     timestamp        text
    xx            18:09           httpsasdadsa what
    xxx           18:09           httpsasdadsa where
    xxxx          18:07           httpsasdadsa when

我的代码:

import string
string.punctuation
import pandas as pd
import re

df = pd.read_csv('data.csv')

for i in range (0-4586):
    data = (df['text'][i])
    x = re.sub("^https"," ", str(data))
    df['text'][i]= x

但它什么也没做,什么都没有改变。 我想在 re.sub 之后这样做:

  username     timestamp        text
0 xx           18:09           what
1 xxx          18:09           where
2 xxxx         18:07           when

【问题讨论】:

    标签: regex python-3.x pandas dataframe


    【解决方案1】:

    假设我们有一个数据框:

    df
        username    timestamp   text
    0   xx          18:09       httpsasdadsa what
    1   xxx         18:09       httpsasdadsa where
    2   xxxx        18:07       httpsasdadsa when
    

    那你可以试试pandas.Series.str.replace:

    df.loc[df.index<4586,"text"] = df.loc[df.index<4586,"text"].str.replace("^https.*\s","")
    df
    
        username    timestamp   text
    0   xx          18:09       what
    1   xxx         18:09       where
    2   xxxx        18:07       when
    

    【讨论】:

    • 它仍然没有任何变化,不知道为什么。还要别的吗?谢谢你的帮助。非常感谢
    • df.index 的输出是什么?
    • 我在 spyder 上运行它,所以如果我尝试在 df.loc[df.index
    • 试试df["text"] = df["text"].str.replace("^https.*\s","")
    • 还是那个先生。 :|
    猜你喜欢
    • 2015-06-16
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多