1

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

0

2 Answers 2

3

Explode

df = pd.DataFrame({'asia':[['china','india','australia']],
              'europe':[['spain','uk','russia','france','germany']],
              'americas':[['canada','usa','mexico']]
            }).transpose().explode(0)
Sign up to request clarification or add additional context in comments.

Comments

0

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')
            )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.