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

Time:03-01

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...

CodePudding user response:

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

CodePudding user response:

Use np.reshape:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.reshape(my_list, (-1, 7)))
print(df)

# 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
  • Related