[SOLVED] How to reshape a this list vertical to horizontal

Issue

i have a list arranged like this:

0         [1, 6]
1         [2, 7]
3         [3, 8]
4         [4, 9]
5         [5, 10]

but I am trying to transpose like this:

0         [1, 2, 3, 4, 5]
1         [6, 7, 8, 9, 10]

Please help…

Solution

IIUC, to me this looks like a single column dataframe with a list of two elements in each row of the dataframe:

df = pd.DataFrame({'col1':[[1, 6], [2 ,7], [3, 8], [4, 9],[5, 10]]})

Try this:

pd.concat([df['col1'].str[i].rename(f'{i}').to_frame().T 
           for i in range(len(df.iloc[0, 0]))]).agg(list, axis=1)

Output:

0     [1, 2, 3, 4, 5]
1    [6, 7, 8, 9, 10]
dtype: object

Answered By – Scott Boston

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *