0

Suppose that I have the following code

import pandas as pd

cars = {'Index': [1, 2, 3, 4],
        'Values': ['A, B, C, D', 'A, B', 'C', 'D']
        }

df = pd.DataFrame(cars, columns = ['Index', 'Values'])

print (df)

which creates a DataFrame that looks like this...

   Index      Values
0      1  A, B, C, D
1      2        A, B
2      3           C
3      4           D

How do I take that Dataframe, and create a new one which looks like this...

   Index      Values
0      1           A
1      1           B
2      1           C
3      1           D
4      2           A
5      2           B
6      3           C
7      4           D

1 Answers1

0
df.Values = df.Values.str.split(",")
df = df.explode('Values').reset_index(drop=True)


 Index Values
0      1      A
1      1      B
2      1      C
3      1      D
4      2      A
5      2      B
6      3      C
7      4      D
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
  • While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Mustafa Apr 22 '20 at 02:12