Constructing 3D Pandas DataFrame

后端 未结 3 492
名媛妹妹
名媛妹妹 2020-12-04 19:45

I\'m having difficulty constructing a 3D DataFrame in Pandas. I want something like this

A               B               C
start    end    start    end    st         


        
3条回答
  •  日久生厌
    2020-12-04 20:29

    First, I think you need to fill C to represent missing values

    In [341]: max_len = max(len(sublist) for sublist in C)
    In [344]: for sublist in C:
         ...:     sublist.extend([np.nan] * (max_len - len(sublist)))
    
    In [345]: C
    Out[345]: 
    [[7, 11, 56, 45],
     [20, 21, 74, 12],
     [42, nan, nan, nan],
     [52, nan, nan, nan],
     [90, 213, 9, nan],
     [101, 34, 45, nan]]
    

    Then, convert to a numpy array, transpose, and pass to the DataFrame constructor along with the columns.

    In [288]: C = np.array(C)
    In [289]: df = pd.DataFrame(data=C.T, columns=pd.MultiIndex.from_tuples(zip(A,B)))
    
    In [349]: df
    Out[349]: 
         one         two       three     
       start  end  start  end  start  end
    0      7   20     42   52     90  101
    1     11   21    NaN  NaN    213   34
    2     56   74    NaN  NaN      9   45
    3     45   12    NaN  NaN    NaN  NaN
    

提交回复
热议问题