Home > Mobile >  How to replicate rows based on the values of a column
How to replicate rows based on the values of a column

Time:01-20

due a dataframe:

data={'a':'1',
      'b': '1,2,3',
      'c':'2'}

Out:    a    b    c
     0  1  1,2,3  2

I would like to replicate rows for each value in the column b:

Out:    a    b    c
     0  1    1    2
     1  1    2    2
     2  1    3    2

Is there a way to do this?

CodePudding user response:

If your column is a string of comma separated values as given, you can use:

>>> data={'a':'1',
...       'b': '1,2,3',
...       'c':'2'}
>>> df = pd.DataFrame([data])
>>> df['b'] = df['b'].str.split(',')
>>> df.explode('b')

out:
   a  b  c
0  1  1  2
0  1  2  2
0  1  3  2

CodePudding user response:

df={'a':'1','b': '1,2,3','c':'2'}
df = pd.DataFrame([data])
df.assign(b=df.b.str.split(",")).explode("b")
  •  Tags:  
  • Related