Reputation: 51
I am new to python pandas and facing this issue
Year, Category, Law, col_1, col_2, col_3, col_4
2015, Contraception, Law_1, 'CO MO VA', '' , 'XY', ''
Is there any way I can get this:
Year, Category, Law, state, stage
2015, Contraception, Law_1, CO, col_1
2015, Contraception, Law_1, MO, col_1
2015, Contraception, Law_1, VA, col_1
2015, Contraception, Law_1, XY, col_3
Upvotes: 2
Views: 363
Reputation: 51
df = pd.melt(frame=data, id_vars=data.columns[:3], value_name='State',var_name='Stage')
df.State = df.State.str.split()
df = df.explode('State')
df.dropna(subset = ["State"], inplace=True)
0.25.0
as explode is supported in latest version only.Upvotes: 2
Reputation: 5183
df = df.melt(id_vars=df.columns[:3], var_name='stage', value_name='state')
df.stage = df.stage.str.split(' ')
df = df.explode('state')
Upvotes: 0