在MultiIndex DataFrame/Series中添加一行

use*_*991 12 python indexing pandas

我想知道是否有一种等效方法可以使用MultiIndex向Series或DataFrame添加一行,因为只有一个索引,即使用.ix或.loc?

我认为自然的方式会是这样的

row_to_add = pd.MultiIndex.from_tuples()
df.ix[row_to_add] = my_row
Run Code Online (Sandbox Code Playgroud)

但这引发了一个KeyError.我知道我可以使用.append(),但我觉得使用.ix []或.loc []更加整洁.

这里有一个例子:

>>> df = pd.DataFrame({'Time': [dt.datetime(2013,2,3,9,0,1), dt.datetime(2013,2,3,9,0,1)], 'hsec': [1,25], 'vals': [45,46]})
>>> df
                 Time  hsec  vals
0 2013-02-03 09:00:01     1    45
1 2013-02-03 09:00:01    25    46

[2 rows x 3 columns]
>>> df.set_index(['Time','hsec'],inplace=True)
>>> ind = pd.MultiIndex.from_tuples([(dt.datetime(2013,2,3,9,0,2),0)],names=['Time','hsec'])
>>> df.ix[ind] = 5

Traceback (most recent call last):
  File "<pyshell#201>", line 1, in <module>
    df.ix[ind] = 5
  File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing.py", line 96, in __setitem__
    indexer = self._convert_to_indexer(key, is_setter=True)
  File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing.py", line 967, in _convert_to_indexer
    raise KeyError('%s not in index' % objarr[mask])
KeyError: "[(Timestamp('2013-02-03 09:00:02', tz=None), 0L)] not in index"
Run Code Online (Sandbox Code Playgroud)

use*_*991 16

更新因为.ix已弃用[DataFrame.loc][1]改为使用:

# 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
Run Code Online (Sandbox Code Playgroud)


Jef*_*eff 13

您必须指定一个元组才能使多索引工作(并且您必须完全指定所有轴,例如,这:是必要的)

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
Run Code Online (Sandbox Code Playgroud)

更容易重新索引和/或连接/追加新的数据帧.通常设置(使用这种放大),只有在使用少量值进行设置时才有意义.因为这样做时会复制一份.