首页 > 解决方案 > 大熊猫中的爆炸列表列

问题描述

考虑以下示例

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

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

所需的输出如下所示。如您所见hello,与 匹配therehasta与 匹配la vista等。我们获得了三行,因为第一个列表中有两个元素,而第二个列表中只有一个。

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

我怎样才能做到这一点?谢谢!

标签: pythonpandas

解决方案


这是一种方法:

  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

推荐阅读