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

Converting a Python list into a pandas dataframe while specifying certain elements as row labels

I have the below list called my_list and want to convert it to a new pandas dataframe where the strings starting with ‘I=’ will become the dataframe’s row labels.

my_list=['I=113',
 'PLAN=1',
 'A=0PDFGB',
 'B=23FGC',
 'C=26TGFGD',
 'D=19TGE',
 'E=18TGA',
 'I=120',
 'PLAN=2',
 'A=0PDFGB',
 'B=23FGC',
 'C=26TGFGD',
 'D=19TGE',
 'E=18TGA',
 'I=113',
 'PLAN=2',
 'A=0PDFGB',
 'B=23FGC',
 'C=26TGFGD',
 'D=19TGE',
 'E=18TGA']

The output will look like the below:

--------------------------------------------------------
I=113|PLAN=1|A=0PDFGB|B=23FGC|C=26TGFGD|D=19TGE|E=18TGA
--------------------------------------------------------
I=120|PLAN=2|A=0PDFGB|B=23FGC|C=26TGFGD|D=19TGE|E=18TGA
-------------------------------------------------------

and so on…

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 :

We could use a loop cut the list into sublists and use the DataFrame constructor:

tmp = []
for item in my_list:
    if item.startswith('I'):
        tmp.append([])
    tmp[-1].append(item)
out = pd.DataFrame(tmp)

Output:

       0       1         2        3          4        5        6
0  I=113  PLAN=1  A=0PDFGB  B=23FGC  C=26TGFGD  D=19TGE  E=18TGA
1  I=120  PLAN=2  A=0PDFGB  B=23FGC  C=26TGFGD  D=19TGE  E=18TGA
2  I=113  PLAN=2  A=0PDFGB  B=23FGC  C=26TGFGD  D=19TGE  E=18TGA
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