考虑下面的例子
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 个元素。 Mylist1
和 mylist2
始终具有相同数量的元素(在此示例中:第一个 obs 中为 2,第二个 obs 中为 1)。
所需的输出如下所示。如您所见,hello
与 there
匹配,hasta
与 la vista
匹配等。我们得到三行,因为第一个列表中有两个元素,而刚好一个在第二个。
Out[241]:
exploded
0 hello there
1 hasta la vista
2 one shot
我该怎么做? 谢谢!
答案 0 :(得分:1)
这是一种方法:
Explode
数据框 vertically
join
沿轴 1
的字符串。df = df.apply(pd.Series.explode).apply(' '.join, 1)
0 hello there
0 hasta la vista
1 one shot
dtype: object