【问题标题】:Concatenate words and phrases based on conditions (Python 3, Pandas)根据条件连接单词和短语(Python 3、Pandas)
【发布时间】:2014-09-11 03:13:30
【问题描述】:

假设我有一个这样的数据框列表,称为 Single_Words:

Words           
The               
Man           
Was             
Funny           
and             
Handsome        

然后是另一个像这样的单独的数据框列表,称为 Bigrams:

Words               
The Comedian         
The Man              
Handsome Dan         
Funny Guy            
Man Down             
The Jokester         
Comedians Are     

我想要做的是遍历 Single_Words 数据框中的每个单词,然后将其连接到第二个列表中的二元组,其中只有二元组的第一个单词是相同的。

所以这是一个示例输出,使用第一个数据帧中的单词“The”并遍历第二个数据帧将产生一个新列表,如下所示:

Words                     
The The Comedian          
The The Man               
The The Jokester          

使用第一个数据帧中的“Man”并遍历第二个数据帧将给出:

  Words   
Man Down 

一旦我有了这个新列表并遍历了初始列表,我计划通过再次遍历原始二元表(最多 5 次)来冲洗并重复此过程。所以回到“The”的例子,第二次迭代会像这样添加到列表中

      Words    
The The Comedian          
The The Man               
The The Jokester                    
The The Man Man Down 
The The Comedians Comedians Are

有人有什么建议吗?

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    这行得通,我会尝试找到更好的方法。 基本上我使用re 来搜索完整的单词(例如不匹配Handsome)并构造一个字典并从该字典创建一个新的df:

    In [108]:
    
    import re
    temp = {'Words':[]}
    def func(x):   
        for w in list(df1.Words):
            if re.search(r'\b'+x+r'\b', w):
                # just add the entry if the dict is empty
                if len(temp['Words']) == 0:
                    temp['Words'] = [x + ' ' + w]
                else:
                    t = temp['Words']
                    t.append(x + ' ' + w)
                    temp['Words'] = t
    
    df.Words.apply(func)
    total = pd.DataFrame(temp)
    total
    Out[108]:
                       Words
    0       The The Comedian
    1            The The Man
    2       The The Jokester
    3            Man The Man
    4           Man Man Down
    5        Funny Funny Guy
    6  Handsome Handsome Dan
    

    【讨论】:

    • 嗨,Ed,感谢您的反馈 :) 所以有些事情我很好奇: 1.) 3 输出是“Man The Man”——这种方法实际上是如何搜索单词的? 2.)其次,我必须说我很困惑我应该在哪里将我的数据框变量插入到这段代码中?这个方法是遍历一个列表还是我必须手动输入每个单词?抱歉所有问题,谢谢!
    • 您没有指定匹配的要求,所以我假设您想要整个单词匹配,正则表达式中的 \b 在单词的开头和结尾查找中断,这将停止 @987654324 @匹配Handsome。由于 df 的大小不同,您可以修改我的代码以返回系列或列表,以便为每一行提供一个匹配列表。是的,这会手动迭代第二个 df 中具有二元组的列表
    • 谢谢!我很感激
    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多