在熊猫中爆炸列表列

时间:2021-07-06 17:39:22

标签: python pandas

考虑下面的例子

dftest = pd.DataFrame({'mylist1' : [['hello', 'hasta'], 'one'],
                       'mylist2' : [['there', 'la vista'], 'shot']})

dftest
Out[240]: 
          mylist1            mylist2
0  [hello, hasta]  [there, la vista]
1             one               shot

我想分解两列,以便将 mylist1 中的第 n 个元素连接到 mylist2 中的第 n 个元素。 Mylist1mylist2 始终具有相同数量的元素(在此示例中:第一个 obs 中为 2,第二个 obs 中为 1)。

所需的输出如下所示。如您所见,hellothere 匹配,hastala vista 匹配等。我们得到三行,因为第一个列表中有两个元素,而刚好一个在第二个。

Out[241]: 
         exploded
0     hello there
1  hasta la vista
2        one shot

我该怎么做? 谢谢!

1 个答案:

答案 0 :(得分:1)

这是一种方法:

  1. Explode 数据框 vertically
  2. join 沿轴 1 的字符串。
df = df.apply(pd.Series.explode).apply(' '.join, 1)

输出:

0       hello there
0    hasta la vista
1          one shot
dtype: object
相关问题