熊猫:如何添加一个新列,结合其他列的几个列表?

时间:2017-11-30 10:30:38

标签: python pandas

我想将包含列表的多个列的内容合并到一个只包含一个List的新列中。

  Name            list0         list1                     list2
0    a  [Now, Now, Now]          None  [works!, works!, works!]
1    b  [Now, Now, Now]  [it, it, it]                      None
2    c  [Now, Now, Now]  [it, it, it]  [works!, works!, works!]

新列应如下所示:

0              [Now, Now, Now, works!, works!, works!]
1                          [Now, Now, Now, it, it, it]
2    [Now, Now, Now, it, it, it, works!, works!, wo...

我的解决方案:

#Column of empty lists
new['helper']=np.empty((len(new), 0)).tolist()

#Missing values to empty lists
new['list0']=new['list0'].fillna(new['helper'])
new['list1']=new['list1'].fillna(new['helper'])
new['list2']=new['list2'].fillna(new['helper'])

#Add Lists
new['together']=new['list0']+new['list1']+new['list2']

但必须有更快或更好的解决方案! 任何提示?

1 个答案:

答案 0 :(得分:0)

new['together']=new[['list0', 'list1', 'list2']].apply(lambda x: ''.join(x), axis=1)

应该更快地加入他们