Home > Software engineering >  Iterating list to create df
Iterating list to create df

Time:12-31

I have a variable <class 'list'> that comes from a post request API in GraphQL that looks like this:

  [
    {'duration': 0, 
     'phase': 
        {
            'name': 'Start form'
        }
    }, 
    {'duration': 441, 
     'phase': 
        {
            'name': 'Análise do SAC - Mesas'
        }
    }, 
    {'duration': 126057, 
     'phase': 
        {
            'name': 'Análise do SAC - Industrial'
        }
    }
 ]

How can I iterate thru this list and create a dataframe that looks like this:

Start form Análise do SAC - Mesas Análise do SAC - Industrial
0 441 126057

I need to create the df like this because I will merge with another df

Also, I'm curious, what's the need of this list organization? Like a list of lists? List of dict?

Thanks in advance!!

CodePudding user response:

Consider the following code which will produce the output you want:

import pandas as pd

response =  [
    {'duration': 0, 
     'phase': 
        {
            'name': 'Start form'
        }
    }, 
    {'duration': 441, 
     'phase': 
        {
            'name': 'Análise do SAC - Mesas'
        }
    }, 
    {'duration': 126057, 
     'phase': 
        {
            'name': 'Análise do SAC - Industrial'
        }
    }
 ]
 
data = {}
for obj in response:
    data[obj["phase"]["name"]] = [obj["duration"]]
     
df = pd.DataFrame(data)
print(df.to_string(index=False))

CodePudding user response:

Use:

df = pd.json_normalize(l)
df = df.set_index('phase.name').T.reset_index(drop=True)

OUTPUT

phase.name  Start form  Análise do SAC - Mesas  Análise do SAC - Industrial
0                    0                     441                       126057

If want to rename axis you can then use:

df.rename_axis(None, axis=1, inplace=True)

OUTPUT

   Start form  Análise do SAC - Mesas  Análise do SAC - Industrial
0           0                     441                       126057
  • Related