Search code examples
pythonlist

Nested list in Python - Transpose nested list


I have a below nested list:

list = [Language:'Tamil'
        Capital: 'Chennai' 
        Place: 'Chennai', 'Vellore', 'Trichy', 'Madurai' 
]

I'm expecting to transpose it as:

Language     Capital     Place
Tamil        Chennai     Chennai
Tamil        Chennai     Vellore
Tamil        Chennai     Trichy
Tamil        Chennai     Madurai 

Tried converting to pandas dataframe:

df = pd.DataFrame(list)

The result is

Language    Capital       Place  
Tamil       Chennai       ['Chennai', 'Vellore', 'Trichy', 'Madurai']  

How can I transpose each list of values in a new row for the place?


Solution

  • First:

    data = {
        'Language': 'Tamil',
        'Capital': 'Chennai',
        'Place': ['Chennai', 'Vellore', 'Trichy', 'Madurai']
    }
    

    Next, you can create a DataFrame by repeating the values for Language and Capital and expanding the Place list into multiple rows:

    df = pd.DataFrame({
        'Language': [data['Language']] * len(data['Place']),
        'Capital': [data['Capital']] * len(data['Place']),
        'Place': data['Place']
    })
    

    Output:

         Language  Capital    Place
    0    Tamil     Chennai    Chennai
    1    Tamil     Chennai    Vellore
    2    Tamil     Chennai    Trichy
    3    Tamil     Chennai    Madurai