How to create a dataframe from a nested list of multiple common elements

Hertzeh :

Say I have any nested list, for example

A = [[120, 'Date1', 1.03], [120, 'Date2', 1.04], [120, 'Date3', 1.02], [240, 'Date1', 1.06], [240,'Date2', 0.98],
     [240, 'Date3', 1.04], [381, 'Date2', 1.03], [381, 'Date3', 0.85]]

The first element of each sub-list is the stock number, the second the date, and the third a corresponding value. I want to create a dataframe where the column headings are the stock number, row headings are the date and the elements are the corresponding (third element) values. I am not directly sure on how I would do this. I want to form something like this:

      120     240    381
Date1 1.03    1.06   NaN
Date2 1.04    0.98   1.03
Date3 1.02    1.04   0.85

But I want to form this for any size nested list, so I can't just type in each variable for the dataframe. Any help would be greatly appreciated.

Thank you.

jezrael :

Create DataFrame by constructor and then DataFrame.pivot with DataFrame.rename_axis:

df = pd.DataFrame(A).pivot(1,0,2).rename_axis(index=None, columns=None)
print (df)
        120   240   381
Date1  1.03  1.06   NaN
Date2  1.04  0.98  1.03
Date3  1.02  1.04  0.85

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16105&siteId=1