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

How to transform list to other format in python

I get data in this format..

ListA =
[
    [('test1', 'aaa', 'A'),('test2', 'bbb', 'B'),('test3', 'ccc', 'C')],
    [('test4', 'ddd', 'D'),('test5', 'eee', 'E'),('test6', 'fff', 'F')],
    [('test7', 'ggg', 'A'),('test8', 'hhh', 'B'),('test9', 'ppp', 'C')]
]

and I would like to transform to this format

ID, ColA, ColB, ColC,
1, 'test1', 'aaa', 'A'
1, 'test2', 'bbb', 'B'
1, 'test3', 'ccc', 'C'
2, 'test4', 'ddd', 'D'
2, 'test5', 'eee', 'E'
2, 'test6', 'fff', 'F'
3, 'test7', 'ggg', 'A'
3, 'test8', 'hhh', 'B'
3, 'test9', 'ppp', 'C'

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

>Solution :

You can use itertools.chain:

from itertools import chain
df = pd.DataFrame(chain.from_iterable(ListA),
                  columns=['ColA', 'ColB', 'ColC'])

output:

    ColA ColB ColC
0  test1  aaa    A
1  test2  bbb    B
2  test3  ccc    C
3  test4  ddd    D
4  test5  eee    E
5  test6  fff    F
6  test7  ggg    A
7  test8  hhh    B
8  test9  ppp    C

with the index (can handle uneven list lengths):

from itertools import chain
import numpy as np

idx = np.repeat(np.arange(len(ListA))+1, list(map(len, ListA)))

df = pd.DataFrame(chain.from_iterable(ListA),
                  columns=['ColA', 'ColB', 'ColC'],
                  index=idx).rename_axis('ID')

output:

     ColA ColB ColC
ID                 
1   test1  aaa    A
1   test2  bbb    B
1   test3  ccc    C
2   test4  ddd    D
2   test5  eee    E
2   test6  fff    F
3   test7  ggg    A
3   test8  hhh    B
3   test9  ppp    C
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