我有一个关于之间差异的问题df.loc
and df.at
关于具有多重索引的数据帧。我一直在 stackoverflow 上查看一些精彩的资源,但它似乎并没有阐明我的问题。尤其是这个...熊猫 .at 与 .loc https://stackoverflow.com/questions/37216485/pandas-at-versus-loc(或者至少我不完全理解这里显示的内容)。
根据熊猫文档,https://pandas-docs.github.io/pandas-docs-travis/ generated/pandas.DataFrame.at.html https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.DataFrame.at.html, df.at
应该返回奇异值,并且它比df.loc
,所以我倾向于使用df.at
。让我展示一下我的困惑,因为它适用于使用df.at
带有多重索引。
我有以下数据框:
df = pd.DataFrame({'field1':['foo']*6, 'field2':['bar']*6, 'field3':
['a','a','b','b','b','c'],'value1':[0.4,0.5,0.4,0.7,.9,.4],'value2':
[4000,4000,9000,9000,9000,10000]}, index=range(6))
df
Out[329]:
field1 field2 field3 value1 value2
0 foo bar a 0.4 4000
1 foo bar a 0.5 4000
2 foo bar b 0.4 9000
3 foo bar b 0.7 9000
4 foo bar b 0.9 9000
5 foo bar c 0.4 10000
我想使用 MultiIndex 访问此数据框,因此我正在执行以下操作:
df = df.set_index(['field1','field2','field3'])
所以现在我想访问value1
in my df
at ('foo','bar','c')
这是一个奇异值,并且它是错误的。
df.at[('foo','bar','c'),'value1']
Traceback (most recent call last):
File "<ipython-input-344-921b8b658a49>", line 1, in <module>
df.at[('foo','bar','c'),'value1']
File "C:\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1610,
in __getitem__
return self.obj.get_value(*key, takeable=self._takeable)
File "C:\Anaconda2\lib\site-packages\pandas\core\frame.py", line 1836, in
get_value
return engine.get_value(series.get_values(), index)
File "pandas\index.pyx", line 103, in pandas.index.IndexEngine.get_value
(pandas\index.c:3234)
File "pandas\index.pyx", line 111, in pandas.index.IndexEngine.get_value
(pandas\index.c:2931)
File "pandas\index.pyx", line 152, in pandas.index.IndexEngine.get_loc
(pandas\index.c:3830)
File "pandas\index.pyx", line 170, in
pandas.index.IndexEngine._get_loc_duplicates (pandas\index.c:4154)
TypeError: only integer arrays with one element can be converted to an index
我假设这返回一个系列对象,它不能表示单个值?这只是我的假设,给出了输出df.loc
.
df.loc[('foo','bar','c')]['value1']
Out[345]:
field1 field2 field3
foo bar c 0.4
Name: value1, dtype: float64
现在,如果我没有使用 MultiIndex,我认为这个问题不会出现......
无论如何,这附近有什么,或者我显然错过了什么?谢谢