gpt4 book ai didi

Python 对 pandas 数据框中的单词进行单数化

转载 作者:行者123 更新时间:2023-12-01 01:42:40 25 4
gpt4 key购买 nike

我想将“短语”列中的复数单词转换为单数单词。如何迭代每一行和每个项目?

my_data = [('Audi Cars', 'Vehicles'),
('Two Parrots', 'animals'),
('Tall Buildings', 'Landmark')]
test = pd.DataFrame(my_data)
test.columns = ["Phrase","Connection"]
test

我试过了

test["Phrase"] = test["Phrase"].str.lower().str.split()
import inflection as inf
test["Phrase"].apply(lambda x:inf.singularize([item for item in x]))

我想要的输出是

Phrase:         Connection:
Audi Car Vehicles
Two Parrot animals
Tall Building Landmark

请注意,我只想单数一列阶段

最佳答案

略有变化 -

test['clean'] = test['Phrase'].apply(lambda x: ' '.join([inf.singularize(item) for item in x.split()]))

输出

           Phrase Connection          clean
0 Audi Cars Vehicles Audi Car
1 Two Parrots animals Two Parrot
2 Tall Buildings Landmark Tall Building

说明

在您现有的代码中,您正在执行此操作 -

test["Phrase"].apply(lambda x:inf.singularize([item for item in x]))

让我们看第一个例子,看看会发生什么。在本例中,x 将为 Audi Cars -

[x 中的项目的项目] 返回字符列表 - ['A', 'u', 'd', 'i', ' ', 'C', 'a', 'r', 's'] 因此 singularize 不起作用,因为它仅适用于字符。

技巧是使用 x.split() 来分割单词,然后将 singularize 放入列表理解中。

最后执行 ' '.join() 来取回字符串。

关于Python 对 pandas 数据框中的单词进行单数化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51707384/

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