0

Is there any possibility to duplicate part of the row based on the delimiter

For example, if I have df like this:

Cars             Country       Trans                     trans_id
Alto             Australia     Automatic & Manual        auto & man

I want to convert each row on the & delimiter into 2 rows and keep the other columns same

The desired output should be:

    Cars             Country       Trans                     trans_id        New_Trans     NewTransID
    Alto             Australia     Automatic & Manual        auto & man      Automatic     auto
    Alto             Australia     Automatic & Manual        auto & man      Manual        man
s_khan92
  • 969
  • 8
  • 21

1 Answers1

2

Use:

df = (df.assign(new_Trans = df['Trans'].str.split(' & '),
                new_trans_id = df['trans_id'].str.split(' & '))
        .explode(['new_Trans','new_trans_id']))
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252