0

I have a dataframe where one of the columns has 2 or more elements inside a list format, like the following:

                     Email                           Country
0              [email protected]                    [Czech Republic, Singapore, United Kingdom]
1             [email protected]                 [Singapore, United Kingdom]   
2              [email protected]                  [United Kingdom, Czech Republic]

I need to do the following: - Duplicate the number of rows by list lenght in "Country" (so for example, first row would be duplicated twice) - For each row, I would need to have as index one of the list elements (so for example, one of them would be Czech Republic, the other row Singapore and the other row United Kingdow as index).

Does someone know how could I do it?

Thank you!

1 Answer 1

1

You can use .explode() to 'duplicate' the rows:

import pandas as pd

df = pd.DataFrame([['[email protected]', ['Czech Republic', 'Singapore', 'United Kingdom']],
                   ['[email protected]', ['Singapore', 'United Kingdom']],
                   ['[email protected]', ['United Kingdom', 'Czech Republic']]
                  ], columns = ['Email', 'Country'])
df.explode('Country')

Result:

                Email         Country
0      [email protected]  Czech Republic
0      [email protected]       Singapore
0      [email protected]  United Kingdom
1  [email protected]       Singapore
1  [email protected]  United Kingdom
2    [email protected]  United Kingdom
2    [email protected]  Czech Republic

To set the index use:

df.explode('Country').set_index('Country')
Sign up to request clarification or add additional context in comments.

3 Comments

Hello Rene, thanks for the quick reply! I am getting the error that dataframe has no attribute "explode"
What version of pandas do you use?
Yeah, just checked I need to update Pandas version, thanks!

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.