Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list in columns to vertical shape?

One of the columns in my pandas dataframe contains a list. And I want to expand it and convert vertical shape like below. How to do it?

Before(code):

import pandas as pd
pd.DataFrame({
    'col1':['fruit', 'veicle', 'animal'],
    'col2':['apple', 'bycicle', 'cat'],
    'col3':[1,4,2],
    'list':[
        [10, 20],
        [1.2, 3.0, 2.75],
        ['tommy', 'tom']
    ]
})

Before(table):

    |col1  |col2   |col3|list            |
    |------|-------|----|----------------|
    |fruit |apple  |   1|[10, 20]        |
    |veicle|bicycle|   4|[1.2, 3.0, 2.75]|
    |animal|cat    |   2|['tommy', 'tom']|

After

    |col1  |col2   |col3|list   |
    |------|-------|----|-------|
    |fruit |apple  |   1|10     |
    |fruit |apple  |   1|20     |
    |viecle|bycicle|   4|1.2    |
    |viecle|bycicle|   4|3.0    |
    |viecle|bycicle|   4|2.75   |
    |animal|cat    |   2|'tommy'|
    |animal|cat    |   2|'tom   |

Note1: Length and type of lists is different.

Note2: I can NOT modify the code for generating datafarme.

Thank you for reading.

like image 866
AkiraIsaka Avatar asked Dec 05 '25 09:12

AkiraIsaka


1 Answers

You can set_index of first three columns and then apply pd.Series to the column of list and then stack them.

df.set_index(['col1','col2','col3'])['list'].apply(pd.Series).stack().reset_index().drop('level_3',axis=1)

Output:

     col1     col2  col3      0
0  fruit   apple    1     10   
1  fruit   apple    1     20   
2  veicle  bycicle  4     1.2  
3  veicle  bycicle  4     3    
4  veicle  bycicle  4     2.75 
5  animal  cat      2     tommy
6  animal  cat      2     tom  
like image 160
Bharath Avatar answered Dec 07 '25 23:12

Bharath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!