我想知道是否有一种等效的方法可以将行添加到带有 MultiIndex 的 Series 或 DataFrame 中,就像使用单个索引一样,即使用 .ix 或 .loc?
我认为自然的方式应该是这样的
row_to_add = pd.MultiIndex.from_tuples()
df.ix[row_to_add] = my_row
但这会引发 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"
最佳答案
您必须为多索引指定一个元组才能工作(并且您必须完全指定所有轴,例如 :
是必需的)
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
虽然重新索引和/或连接/附加新数据框更容易。一般设置(通过这种放大),只有在使用少量值时才有意义。因为这会在您执行此操作时生成副本。
关于python - 向 MultiIndex DataFrame/Series 添加一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917700/