Home > Enterprise >  How to reshape a this list vertical to horizontal
How to reshape a this list vertical to horizontal

Time:03-25

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

CodePudding user response:

In numpy, for transposing you can do:

array.T

CodePudding user response:

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
  • Related