Assign new values to slice from MultiIndex DataFrame

后端 未结 1 459
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 10:13

I would like to modify some values from a column in my DataFrame. At the moment I have a view from select via the multi index of my original df (and modif

1条回答
  •  梦如初夏
    2021-02-05 10:49

    Sort the frame, then select/set using a tuple for the multi-index

    In [12]: df = pd.DataFrame(randn(6, 3), index=arrays, columns=['A', 'B', 'C'])
    
    In [13]: df
    Out[13]: 
                      A         B         C
    bar one 0 -0.694240  0.725163  0.131891
        two 1 -0.729186  0.244860  0.530870
    baz one 2  0.757816  1.129989  0.893080
    qux one 3 -2.275694  0.680023 -1.054816
        two 4  0.291889 -0.409024 -0.307302
    bar one 5  1.697974 -1.828872 -1.004187
    
    In [14]: df = df.sortlevel(0)
    
    In [15]: df
    Out[15]: 
                      A         B         C
    bar one 0 -0.694240  0.725163  0.131891
            5  1.697974 -1.828872 -1.004187
        two 1 -0.729186  0.244860  0.530870
    baz one 2  0.757816  1.129989  0.893080
    qux one 3 -2.275694  0.680023 -1.054816
        two 4  0.291889 -0.409024 -0.307302
    
    In [16]: df.loc[('bar','two'),'A'] = 9999
    
    In [17]: df
    Out[17]: 
                         A         B         C
    bar one 0    -0.694240  0.725163  0.131891
            5     1.697974 -1.828872 -1.004187
        two 1  9999.000000  0.244860  0.530870
    baz one 2     0.757816  1.129989  0.893080
    qux one 3    -2.275694  0.680023 -1.054816
        two 4     0.291889 -0.409024 -0.307302
    

    You can also do it with out sorting if you specify the complete index, e.g.

    In [23]: df.loc[('bar','two',1),'A'] = 999
    
    In [24]: df
    Out[24]: 
                        A         B         C
    bar one 0   -0.113216  0.878715 -0.183941
        two 1  999.000000 -1.405693  0.253388
    baz one 2    0.441543  0.470768  1.155103
    qux one 3   -0.008763  0.917800 -0.699279
        two 4    0.061586  0.537913  0.380175
    bar one 5    0.857231  1.144246 -2.369694
    

    To check the sort depth

    In [27]: df.index.lexsort_depth
    Out[27]: 0
    
    In [28]: df.sortlevel(0).index.lexsort_depth
    Out[28]: 3
    

    The last part of your question, assigning with a list (note that you must have the same number of elements as you are trying to replace), and this MUST be sorted for this to work

    In [12]: df.loc[('bar','one'),'A'] = [999,888]
    
    In [13]: df
    Out[13]: 
                        A         B         C
    bar one 0  999.000000 -0.645641  0.369443
            5  888.000000 -0.990632 -0.577401
        two 1   -1.071410  2.308711  2.018476
    baz one 2    1.211887  1.516925  0.064023
    qux one 3   -0.862670 -0.770585 -0.843773
        two 4   -0.644855 -1.431962  0.232528
    

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