Python pandas Multindex column

前端 未结 2 911
栀梦
栀梦 2021-01-23 00:01

First of all, I\'m using python 3.50 in a jupyter notebook.

I want to create a DataFrame for showing some data in a report. I want it to have two index column (Excuse me

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

    There is one major difference between your code and the example: the example passes a numpy array as the input rather than a nested list. In fact, adding np.array(...) around your list works just fine:

    cell_rise_Inv= pd.DataFrame(
            np.array([[0.00483211, 0.00511619, 0.00891821, 0.0449637, 0.205753], 
                      [0.00520049, 0.00561577, 0.010993, 0.0468998, 0.207461],
                      [0.00357213, 0.00429087, 0.0132186, 0.0536389, 0.21384],
                      [-0.0021868, -0.0011312, 0.0120546, 0.0647213, 0.224749],
                      [-0.0725403, -0.0700884, -0.0382486, 0.0899121, 0.313639]]), 
            index=[['transition [ns]'] * 5,
                   [0.0005, 0.001, 0.01, 0.1, 0.5]],
            columns=[['capacitance [pF]'] * 5,
                     [0.01, 0.02, 0.05, 0.1, 0.5]])
    

    I shortened the repeated strings in the index and swapped the order of the index levels, but those are not significant changes.

    EDIT Did a little investigating. If you pass in a nested list (without the np.array call), the call will work without columns and even if columns is a 1D list. For some reason the nested list of two elements is not being interpreted as a multiindex unless the input is an ndarray.

    I filed issue #14467 with pandas based on this question.

    0 讨论(0)
  • 2021-01-23 00:47

    It does appear to be inconsistent. I'd use the pd.MultiIndex constructor from_arrays

    idx = pd.MultiIndex.from_arrays([['transition [ns]'] * 5,
                                     [0.0005, 0.001, 0.01, 0.1, 0.5]])
    col = pd.MultiIndex.from_arrays([[0.01, 0.02, 0.05, 0.1, 0.5],
                                     ['capacitance [pF]'] * 5])
    
    cell_rise_Inv= pd.DataFrame([[0.00483211, 0.00511619, 0.00891821, 0.0449637, 0.205753], 
                                 [0.00520049, 0.00561577, 0.010993, 0.0468998, 0.207461],
                                 [0.00357213, 0.00429087, 0.0132186, 0.0536389, 0.21384],
                                 [-0.0021868, -0.0011312, 0.0120546, 0.0647213, 0.224749],
                                 [-0.0725403, -0.0700884, -0.0382486, 0.0899121, 0.313639]], 
                                index=idx,
                                columns=col)
    cell_rise_Inv
    

    0 讨论(0)
提交回复
热议问题