【问题标题】:Combine two columns containing lists of first and last names into one column that has a list of full names将包含名字和姓氏列表的两列合并为一个包含全名列表的列
【发布时间】:2020-05-28 18:00:41
【问题描述】:

我的数据框有很多列。其中两个是firstlast,分别包含名字和姓氏列表。某些名称丢失并且在其位置上有空白字符串。但是first 列表中的第一项与last 列表中的第一项匹配。

     first                                         last
0    ['john','alex','james','mike','sarah']        ['smith','','connor','michaels','fort']  
1    ['stephen','', 'brittany', 'mandy']           ['chambers','ronalds','','moore']
2    ['guy', 'alec', 'tyrone', 'joe','','amy']     ['lafluer','baldwin','james','montana','','adams']

我想将这些列表合并为一列以获取列name,其中包含名字和姓氏的列表。所以在这个例子中,结果是:

     name                                         
0    ['john smith','alex ','james ','mike michaels','sarah fort']  
1    ['stephen chambers',' ronalds', 'brittany ', 'mandy moore']
2    ['guy lafluer', 'alec baldwin', 'tyrone james', 'joe montana',' ','amy adams']

在 pandas 中组合两个字符串列很容易,使用 df['col3'] = df['col1'] + df['col2'],但我不知道如何做到这一点并以这种方式将两个列表组合在一起。

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    def combiner(l1, l2):
       return [' '.join(x) for x in zip(l1, l2)]
    
    
    df["name"]=df.apply(lambda x: combiner(x["first"], x["last"]), axis=1)
    

    【讨论】:

      【解决方案2】:

      您可以将 ziplist comprehension 一起使用:

      df['name'] = df.apply(lambda x: [m + ' ' + n for m,n in zip(x['first'], x['last'])], 1)
      

      df['name'] = df.apply(lambda x: [' '.join(x) for x in zip(x['first'],x['last'])], 1)
      

      【讨论】:

        【解决方案3】:

        我会尝试两个 for 循环

        l=[[f +' '+ l for f,l in zip(x,y)] for x, y  in zip(df['first'],df['last'])]
        Out[508]: 
        [['john smith', 'alex ', 'james connor', 'mike michaels', 'sarah fort'],
         ['stephen chambers', ' ronalds', 'brittany ', 'mandy moore'],
         ['guy lafluer',
          'alec baldwin',
          'tyrone james',
          'joe montana',
          ' ',
          'amy adams']]
        
        df['name']=l
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-28
          • 1970-01-01
          • 2021-09-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多