gpt4 book ai didi

python - 为什么 pandas 默默地忽略索引过多的 .iloc[i, j] 赋值?

转载 作者:太空狗 更新时间:2023-10-30 01:32:48 25 4
gpt4 key购买 nike

为什么 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

编辑:Reported .

最佳答案

获取值

如果键是元组(如您的示例中所示),则 lociloc 对象的父类(super class)的 __getitem__ 方法在某些时候调用 _has_valid_tuple(self, key)

该方法有如下代码

for i, k in enumerate(key):
if i >= self.obj.ndim:
raise IndexingError('Too many indexers')

这会引发您所期望的 IndexingError

设置值

父类(super class)的 __setitem__ 调用 _get_setitem_indexer 并依次调用 _convert_to_indexer

这个父类(super class)的 _convert_to_indexer 实现有点困惑,但在本例中它返回一个 numpy 数组 [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

现在 indexer 变量是 .loc 情况下的 numpy 数组和 .iloc 情况下的元组。这会导致后续父类(super class)调用 _setitem_with_indexer(indexer, value) 时设置行为的差异。

关于python - 为什么 pandas 默默地忽略索引过多的 .iloc[i, j] 赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38625223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com