代码之家  ›  专栏  ›  技术社区  ›  Ahamed Moosa

Python使pandas数据框中的单词奇异化

  •  1
  • Ahamed Moosa  · 技术社区  · 6 年前

    我想把我的专栏“短语”中的复数转换成单数。如何遍历每一行和每一项?

    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
    

    请注意,我只想使一列奇异 相位

    1 回复  |  直到 6 年前
        1
  •  2
  •   Vivek Kalyanarangan    6 年前

    轻微变化-

    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 -

    [item for item in x] 返回字符列表- ['A', 'u', 'd', 'i', ' ', 'C', 'a', 'r', 's'] 所以 singularize 不起作用,因为它只对字符起作用。

    诀窍就是 x.split() 把单词分开,然后把 奇异化 在列表理解中。

    最后做一个 ' '.join() 把绳子拿回来。