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

前端 未结 2 1773
栀梦
栀梦 2021-01-23 01:41

Say I have any nested list, for example

A = [[120, \'Date1\', 1.03], [120, \'Date2\', 1.04], [120, \'Date3\', 1.02], [240, \'Date1\', 1         


        
相关标签:
2条回答
  • 2021-01-23 01:56

    You can first convert your list to a dict and then build a DataFrame directly.

    d = {}
    [d.setdefault(e[0],{}).update({e[1]:e[2]}) for e in A]
    df = pd.DataFrame(d)
    
            120     240     381
    Date1   1.03    1.06    NaN
    Date2   1.04    0.98    1.03
    Date3   1.02    1.04    0.85
    
    0 讨论(0)
  • 2021-01-23 02:04

    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
    
    0 讨论(0)
提交回复
热议问题