Converting list of string into dataframe row

Question:

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.
.

Asked By: denpy

||

Answers:

Explode

df = pd.DataFrame({'asia':[['china','india','australia']],
              'europe':[['spain','uk','russia','france','germany']],
              'americas':[['canada','usa','mexico']]
            }).transpose().explode(0)
Answered By: wwnde

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')
            )
Answered By: denpy
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.