【问题标题】:Python: Replace multiple words in a column with multiple words from a list and write them to a different column in PandasPython:用列表中的多个单词替换列中的多个单词并将它们写入 Pandas 中的不同列
【发布时间】:2020-10-09 16:29:19
【问题描述】:

我有一个数据框和一个列表如下:

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...

同句和复数的重复无关紧要,唯一重要的是列表中的所有单词都出现在'new_text'列的句子中

我已经尝试过这里的代码:Python: Replace one word in a sentence with a list of words and put thenew sentences in another column in 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>.*)")

提前谢谢你

【问题讨论】:

    标签: python regex pandas list


    【解决方案1】:

    你可以用这个:

    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']
    

    【讨论】:

    • 感谢您的回复,不过,我这里有一个列表和一个数据框,我希望将新句子放在数据框的列中而不是列表中,类似于上面提到的输出。
    • 您只需将此列表添加到数据框中:)
    • 我还看到 print(new) 的输出只使用了列表 'b' 中的单词一次,但我想看到的是所有可能的数字组合都发生在句子
    • 所有数字从 0 到 ?
    • 不是从零开始,而是列表 b 中出现的所有数字,因此例如第一句将更改为:我有两个苹果和三个香蕉,我有三个苹果和四个香蕉,我有四个苹果和五个香蕉,我有五个苹果和一个香蕉,...
    猜你喜欢
    • 2015-05-18
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多