Python: заменить несколько слов в столбце несколькими словами из списка и записать их в другой столбец в Pandas - PullRequest
0 голосов
/ 19 июня 2020

У меня есть фрейм данных и следующий список:

data = {{"text":["I have one apple and two bananas", "this is my apple", "she has three apples","My friend has five apples but she only has one banana"]}
df= pd.DataFrame(data=data, columns=['text'])

my_list = ['one','two','three','four','five']

то, что я хотел бы получить в качестве вывода, - это дополнительный столбец new_text, в котором предложения, содержащие слова из списка, заменяются на каждое слово из my_list, поэтому результат будет выглядеть так:

output:

  text                               new_text
0 I have one apple and two bananas   I have two apple and three bananas, I have three apple and four bananas,I have four apple and five bananas,I have five apple and one bananas,...
1 this is my apple                   this is my apple
2 she has three apples               she has two apples,she has four apples,she has five apples,...

and so on...

повторение одного и того же предложения и множественного числа не имеет значения, важно только то, что все слова из список появляется в предложениях в столбце «новый_текст»

Я пробовал код здесь: Python: заменить одно слово в предложении списком слов и поместить новые предложения в другой столбец в pandas

за исключением шага 1, но находит только первое слово:

 data1 = data['text'].str.extract(
r"(?i)(?P<before>.*)\s(?P<clock>\(?=\bone\b | \btwo\b | \bthree\b | \bfour\b | \bfive\b))\s(?P<after>.*)")

Заранее спасибо

1 Ответ

0 голосов
/ 19 июня 2020

Вы можете использовать это:

a = ["I have one apple and two bananas", "this is my apple",
     "she has three apples", "My friend has five apples but she only has one banana"]

b = ['one','two','three','four','five', 'six']

new = []
for sentence in a:
    newSen = []

    for word in sentence.split():
        if word in b:
             newSen.append(b[b.index(word) + 1])
        else:
            newSen.append(word)

    new.append(' '.join(newSen))

print(new) #output : ['I have two apple and three bananas', 'this is my apple', 'she has four apples', 'My friend has six apples but she only has two banana']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...