adding a row to a MultiIndex DataFrame/Series

前端 未结 2 1093
悲哀的现实
悲哀的现实 2020-12-09 04:23

I was wondering if there is an equivalent way to add a row to a Series or DataFrame with a MultiIndex as there is with a single index, i.e. using .ix or .loc?

I thou

相关标签:
2条回答
  • 2020-12-09 04:41

    You have to specify a tuple for the multi-indexing to work (AND you have to fully specify all axes, e.g. the : is necessary)

    In [26]: df.ix[(dt.datetime(2013,2,3,9,0,2),0),:] = 5
    
    In [27]: df
    Out[27]: 
                              vals
    Time                hsec      
    2013-02-03 09:00:01 1       45
                        25      46
    2013-02-03 09:00:02 0        5
    

    Easier to reindex and/or concat/append a new dataframe though. Generally setting (with this kind of enlargement), only makes sense if you are doing it with a small number of values. As this makes a copy when you do this.

    0 讨论(0)
  • 2020-12-09 05:02

    Update since .ix is depreciated: Today you could do:

    # say you have dataframe x
    x
    Out[78]: 
                  a    b       time
    indA indB                     
    a    i      0.0  NaN 2018-09-12
    b    j      1.0  2.0 2018-10-12
    c    k      2.0  3.0 2018-11-12
         f      NaN  NaN        NaT
    d    i      5.0  NaN        NaT
    
    x.loc[('a','k'),:] = (3.5,6,pd.NaT)
    
    x
    Out[80]: 
                  a    b       time
    indA indB                     
    a    i      0.0  NaN 2018-09-12
    b    j      1.0  2.0 2018-10-12
    c    k      2.0  3.0 2018-11-12
         f      NaN  NaN        NaT
    d    i      5.0  NaN        NaT
    a    k      3.5  6.0        NaT
    
    0 讨论(0)
提交回复
热议问题