S S
S S

Reputation: 235

how to expand a string into multiple rows in dataframe?

i want to split a string into multiple rows.

df.assign(MODEL_ABC = df['MODEL_ABC'].str.split('_').explode('MODEL_ABC'))

my output:
        YEAR   PERIOD   MODEL_ABC     Price       Qty
0      2018      First       A       75.0       25.0

if i run individually for column i'm getting like below but not entire dataframe A B

this is my dataframe df

        YEAR   PERIOD   MODEL_ABC     Price       Qty
0      2018      First       A_B       75.0       25.0

expected output:

        YEAR   PERIOD   MODEL_ABC     Price       Qty
0      2018      First       A       75.0       25.0
1      2018      First       B       75.0       25.0

Upvotes: 0

Views: 188

Answers (1)

Celius Stingher
Celius Stingher

Reputation: 18377

You can do the following, start by transforming the column into a list, so then you can explode it to create multiple rows:

df['MODEL_ABC'] = df['MODEL_ABC'].str.split('_')
df = df.explode('MODEL_ABC')

Upvotes: 1

Related Questions