0

Consider the following example

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

I would like to explode the two columns so that the nth element in mylist1 is concatenated to the nth element in mylist2. Mylist1 and mylist2 always have the same number of elements (in this example: 2 in the first obs, 1 in the second obs).

The desired output is shown below. As you can see hello is matched with there, hasta is matched with la vista, etc. We obtain three rows because there are two elements in the first list, and just one in the second one.

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

How can I do this? Thanks!

1 Answer 1

1

Here's one way:

  1. Explode the dataframe vertically
  2. join strings along axis 1.
df = df.apply(pd.Series.explode).apply(' '.join, 1)

OUTPUT:

0       hello there
0    hasta la vista
1          one shot
dtype: object
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.