Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading