Home > Software design >  pandas get data frame from uneven nested list
pandas get data frame from uneven nested list

Time:06-10

I have a nested list

nl = [[['04-05-2021', '05-05-2021', '06-05-2021'],[2240, 3528, 2800]],[['03-05-2021', '04-05-2021', '05-05-2021'],[123032, 18312, 123872]]]

I want to convert it into a data frame that looks like this:

**Desired output is as follows:**

DATE            1      2
03-05-2021      0     123032
04-05-2021      2240  18312
05-05-2021      3528  123872
06-05-2021      2800  0

The nested list always has two lists one with the date and another with the value. I am trying to create a data frame matching the date and fill nan with zero. I tried the following:

    kk=[]
    for bd in bydatedata:
            kk.append(pd.DataFrame(bd).T)

    kk1=pd.concat(kk,axis=1, ignore_index=True)
    print(kk1)

This gives me the following output:

0             1      2           3
04-05-2021    2240   03-05-2021  123032
05-05-2021    3528   04-05-2021  18312
06-05-2021    2800   05-05-2021  123872

CodePudding user response:

Use lsit comprehension with Series and pass to concat, last replace missing values:

df = pd.concat([pd.Series(b, index=a) for a, b in nl], axis=1).fillna(0).astype(int)
print (df)
               0       1
04-05-2021  2240   18312
05-05-2021  3528  123872
06-05-2021  2800       0
03-05-2021     0  123032
  • Related