Home > Mobile >  from list of list in pandas dataframe to new set of list with multiple columns in pandas
from list of list in pandas dataframe to new set of list with multiple columns in pandas

Time:11-16

I have these values in dataset in a pandas dataframe column

col1
[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]
[[13,14],[15,16],[17,18],[19,20],[21,22],[23,24]]

I want to get 6 elements as list in new columns as rows.

This is the columns that I want to get.

col2                    col3
[1,3,5,7,9,11]          [2,4,6,8,10,12]
[13,15,17,19,21,23]     [14,16,18,20,22,24]

CodePudding user response:

You can use a list comprehension and the DataFrame constructor:

df[['col2', 'col3']] = pd.DataFrame([list(map(list, zip(*l))) for l in df['col1']])

Another approach with :

a = np.dstack(df['col1'].to_numpy())
df['col2'] = a[:,0].T.tolist()
df['col3'] = a[:,1].T.tolist()

Output:

                                                           col1                      col2                      col3
0           [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]       [1, 3, 5, 7, 9, 11]      [2, 4, 6, 8, 10, 12]
1  [[13, 14], [15, 16], [17, 18], [19, 20], [21, 22], [23, 24]]  [13, 15, 17, 19, 21, 23]  [14, 16, 18, 20, 22, 24]
  • Related