Заменить слово в предложении словами из списка и копировать новые предложения в столбце - PullRequest
0 голосов
/ 07 февраля 2020

У меня есть фрейм данных, содержащий предложения в одном столбце, с указанием c слов, которые я извлек из столбца, и третий столбец, содержащий список синонимов для слов во втором столбце:

data= {"sentences":["I am a student", "she is my friend", "that is the new window"],
       "words": ["student","friend", "window"],
       "synonyms":[["pupil"],["comrade","companion"],["brand new","up-to-date","latest"]]}

df= pd.DataFrame(data,columns=['sentences', "words","synonyms"])

Я хотел бы создать еще один столбец, в котором слова в предложениях будут заменены словами из столбцов синонимов:

print(df["new_col"])

Вывод:

I am a pupil

she is my comrade. she is my companion.

this is the brand new window. this is the up-to-date window. this is the latest window.

Я пытался

np.where(df["words"].isin([df["sentences"]), df["sentence"].replace(df["words"].isin([df["sentences"]), df["synonyms"],""  )

но это не дало желаемого результата.

Ответы [ 2 ]

0 голосов
/ 07 февраля 2020

Вы можете сделать это, используя df.apply и используя python map () для итерации по синонимам:

 df['new_column'] = df.apply(lambda row: list(map(lambda word: row[0].replace(row[1], word),  row[2])), axis=1).tolist()

обратите внимание, что вы должны передать axis = 1 в df.apply, чтобы чтобы применить функцию к каждой строке кадра данных: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html

0 голосов
/ 07 февраля 2020

Это не прямая манипуляция с кадрами данных, но вы все равно можете попробовать это:

import pandas as pd

data= {"sentences":["I am a student", "she is my friend", "that is the new window"], "words": ["student","friend", "window"], "synonyms":[["pupil"],["comrade","companion"],["brand new","up-to-date","latest"]]}
df= pd.DataFrame(data,columns=['sentences', "words","synonyms"])

new_col = []
for s in data["sentences"]:
    for index, w in enumerate(data["words"]):
        if w in s:
            a = ". ".join([s.replace(w, syno) for syno in data["synonyms"][index]])
    new_col.append(a)

df["new_col"] = new_col

Вывод:


                sentences    words                         synonyms  \
0          I am a student  student                          [pupil]   
1        she is my friend   friend             [comrade, companion]   
2  that is the new window   window  [brand new, up-to-date, latest]

                                             new_col  
0                                       I am a pupil  
1             she is my comrade. she is my companion  
2  that is the new brand new. that is the new up-...  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...