I have the following continent to country
pd.DataFrame({'asia':[['china','india','australia']],
'europe':[['spain','uk','russia','france','germany']],
'americas':[['canada','usa','mexico']]
}).transpose()
How do I convert into
asia | china
asia | india
asia | australia
europe | spain
europe | uk
etc. .
CodePudding user response:
Explode
df = pd.DataFrame({'asia':[['china','india','australia']],
'europe':[['spain','uk','russia','france','germany']],
'americas':[['canada','usa','mexico']]
}).transpose().explode(0)
CodePudding user response:
Without using explode (i.e. earlier version of Pandas)
(df.set_index(['index'])[0]
.astype(str)
.str.split(',', expand=True)
.stack()
.reset_index(level=-1, drop=True)
.reset_index(name='0')
)