Home > database >  I need to create a Dataframe after iterating through a nested list. I have 6 values that I would lik
I need to create a Dataframe after iterating through a nested list. I have 6 values that I would lik

Time:01-22

I am iterating through a nested list looking to see if a specific value of part of the nested list is empty. If it is empty then I want to take that whole section of the list and extract only parts of the list:

'''

for x in message:

    if len(x[15][0][0][0]) == 0:

        a = x[72][0]

        b = x[15][0]

        c = x[17][0]

        d = x[19][0]

        e = x[73][0]

        f = x[71][0]

        csv  = [a,b,c,d,e,f]

''' I was trying to just use a normal list however I realized that some of the values for a and e are missing and so when I convert it to a csv then eventually the values get messed up.

My goal is to have a data frame with a b c d e f as the column names and then the values below including NaN values. I appreciate any help that you can give me, and if you need any clarifications I would be happy to assist.

CodePudding user response:

You could use list of dicts to create DataFrame.

Store dict for every needed row and create DataFrame from stored rows:

import pandas as pd

frame_rows = []  # List to store dicts
for x in message:
    if len(x[15][0][0][0]) == 0:
        row_data = {
            'a': x[72][0],
            'b': x[15][0],
            'c': x[17][0],
            'd': x[19][0],
            'e': x[73][0],
            'f': x[71][0],
        }
        frame_rows.append(row_data)

df = pd.DataFrame(frame_rows)  # Create dataframe
print(df.head())
  •  Tags:  
  • Related