0

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]

1 Answer 1

1

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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.