0

I have df with three columns:

  • Col 0 - sentence row num
  • Col 1 - Sentence converted to list
  • Col 2 - list of annotations
Col 0 Col1 Col2
1 [This, is, sentence] [l1, l2, l3]
2 [This, is, sentence, too] [l1, l2, l3, l4]

I would like to convert Col1 and Col2 and move each row and its respective annotation to separate row:

Col 0 Col1 Col2
1 This l1
1 is l2
1 sentence l3
2 This l1
2 is l2
2 sentence l3
2 too l4

When I use explode on each column separately one of the columns always does not change.

data2['Col1_exploded'] = (data['Col1'].explode('Col1')) 

And this option does not work too:

data2[['Col1_exploded', 'Col2_exploded']] = (data[['Col1', 'Col2']].explode('Col1', 'Col2'))

2 Answers 2

2

You can pass list of column names to explode:

>>> df.explode(['Col1', 'Col2'])

   Col 0      Col1 Col2
0      1      This   l1
0      1        is   l2
0      1  sentence   l3
1      2      This   l1
1      2        is   l2
1      2  sentence   l3
1      2       too   l4
Sign up to request clarification or add additional context in comments.

Comments

1

you were really close ! this works for me :

df.explode(['Col1', 'Col2'])

result :

    Col 0   Col1    Col2
0   1   This    l1
0   1   is  l2
0   1   sentence    l3
1   2   This    l1
1   2   is  l2
1   2   sentence    l3
1   2   too l4

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.