gpt4 book ai didi

python - 将函数应用于 pandas 数据框列中每行的每个单词

转载 作者:太空宇宙 更新时间:2023-11-03 16:51:58 24 4
gpt4 key购买 nike

我有一个示例数据框,如下所示:

df = pd.DataFrame({
'notes': pd.Series(['speling', 'korrecter']),
'name': pd.Series(['Walter White', 'Walter White']),
})

name notes
0 Walter White This speling is incorrect
1 Walter White Corrector should correct korrecter

我想调整 Peter Norvig 提供的拼写检查器 here 。然后,我想通过检查行中的每个单词来将此函数应用于每一行。我想知道如何在 Python Pandas 上下文中完成此操作?

我希望输出为:

    name                notes
0 Walter White This spelling is incorrect
1 Walter White Corrector should correct corrector

感谢任何意见。谢谢!

最佳答案

您可以使用 str.split 尝试此解决方案,但我认为大型 df 中的性能可能存在问题:

import pandas as pd
import numpy as np

df = pd.DataFrame({
'notes': pd.Series(['This speling is incorrect', 'Corrector should correct korrecter one']),
'name': pd.Series(['Walter White', 'Walter White']),
})
print df
name notes
0 Walter White This speling is incorrect
1 Walter White Corrector should correct korrecter one

#simulate function correct
def correct(x):
return x + '888'

#split column notes and apply correct
df1 = df.notes.str.split(expand=True).apply(correct)
print df1
0 1 2 3 4
0 This888 speling888 is888 incorrect888 NaN
1 Corrector888 should888 correct888 korrecter888 one888

#remove NaN and concanecate all words together
df['notes'] = df1.fillna('').apply(lambda row: ' '.join(row), axis=1)
print df
name notes
0 Walter White This888 speling888 is888 incorrect888
1 Walter White Corrector888 should888 correct888 korrecter888...

关于python - 将函数应用于 pandas 数据框列中每行的每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com