Search code examples
pythonpandasduplicatesrow

duplicate part of the row based on the delimiter in pandas?


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

Solution

  • Use:

    df = (df.assign(new_Trans = df['Trans'].str.split(' & '),
                    new_trans_id = df['trans_id'].str.split(' & '))
            .explode(['new_Trans','new_trans_id']))