为什么在设置或获取具有错误索引数的系列中的项时,pandas的行为会有所不同:
df = pd.DataFrame({'a': [10]})
# df['a'] is a series, can be indexed with 1 index only
# will raise IndexingError, as expected
df['a'].iloc[0, 0]
df['a'].loc[0, 0]
# will raise nothing, not as expected
df['a'].iloc[0, 0] = 1000 # equivalent to pass
df['a'].loc[0, 0] = 1000 # equivalent to df['a'].loc[0] = 1000
# pandas version 0.18.1, python 3.5
Run Code Online (Sandbox Code Playgroud)
编辑:报告.
如果键是一个元组(如您的示例中所示),则和对象__getitem__的超类的方法在某个时刻调用.lociloc_has_valid_tuple(self, key)
这个方法有如下代码
for i, k in enumerate(key):
if i >= self.obj.ndim:
raise IndexingError('Too many indexers')
Run Code Online (Sandbox Code Playgroud)
这IndexingError会引起您的期望。
超类__setitem__依次调用_get_setitem_indexer和_convert_to_indexer。
这个超类的实现_convert_to_indexer有点混乱,但在这种情况下它返回一个 numpy array [0, 0]。
然而,iLoc 索引器的类会覆盖_convert_to_indexer. 该方法返回原始元组...
def _convert_to_indexer(self, obj, axis=0, is_setter=False):
...
elif self._has_valid_type(obj, axis):
return obj
Run Code Online (Sandbox Code Playgroud)
现在,indexer变量是案例的 numpy 数组.loc和案例的元组.iloc。这会导致后续超类调用中的设置行为有所不同_setitem_with_indexer(indexer, value)。
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |