【问题标题】:Cleaning a dataframe in function and returning the dataframe in python在函数中清理数据框并在 python 中返回数据框
【发布时间】:2018-08-09 23:11:01
【问题描述】:

您好,我是 Python 新手,我一直在尝试编写一个函数来清理存储在数据框中的文本数据。

def clean(dataset):
    dataset = dataset.apply(lambda x: " ".join(x.lower() for x in x.split()))
    dataset = dataset.str.replace('[^\w\s]','')
    from nltk.corpus import stopwords
    stop = stopwords.words('english')
    dataset = dataset.apply(lambda x: " ".join(x for x in x.split() if x not in stop))

所以当我像“clean(df['cmets']”这样调用上述函数时,我希望将带有数据框的 cmets 列替换为函数中的已清理文本。 TIA。

【问题讨论】:

标签: python pandas function dataframe series


【解决方案1】:

所以你可以定义你的函数,让它可以接受任何字符串,不管它是否在 Pandas 数据框中。

from nltk.corpus import stopwords

def clean(x):
    x = x.lower()
    x = re.sub('[^\w\s]', '', x)
    stop = stopwords.words('english')
    x = [word for word in x.split() if x not in stop]
    return " ".join(x)

现在您可以将该函数应用于您的字符串列。

test_strs = ['THIS IS A TEST!', 'another test', 'JUS!*(*UDFLJ)']
df = pd.DataFrame(test_strs, columns=['text'])
df['new_text'] = df.apply(lambda x: clean(x.text), axis=1)

这给了我们这个:

text             new_text
THIS IS A TEST! this is a test
another test    another test
JUS!*(*UDFLJ)   jusudflj

【讨论】:

  • 很好,唯一的评论是我认为你应该使用pd.Series.apply 并避免使用lambda,即df['new_text'] = df['text'].apply(clean)
【解决方案2】:

几点建议:

  1. 要使一系列字符串小写,请使用pd.Series.str.lower 等内置方法,而不是pd.Series.applyapply + lambda 是一个隐蔽的低效循环。
  2. 链式操作对于多个操作来说是很自然的。
  3. 将一个系列输入一个函数并只返回一个系列是 Pandas 的反模式。您应该 (a) 输入数据框并修改您的系列,或者 (b) 使用 pd.Series.apply 并按顺序将函数应用于每个元素。

结合这些点,您可以针对给定数据框df 和系列df['comments'] 重构逻辑如下:

def cleaner(df, col_name):
    from nltk.corpus import stopwords
    stop = stopwords.words('english')

    def remove_stops(x, stopwordseq):
        return ' '.join(x for x in x.split() if x not in stopwordseq)

    df[col_name] = df[col_name].str.lower()\
                               .str.replace('[^\w\s]', '')
                               .apply(remove_stops, stop)
    return df

df = df.pipe(cleaner, 'comments')

这 3 行依次将系列转换为小写,仅过滤字母数字和空格,并通过函数 remove_stops 删除停用词。 pd.DataFrame.pipe 是一种通过函数传递数据帧的便捷方法。

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2021-09-04
    相关资源
    最近更新 更多