python - 使用包含数字的字符串进行索引时,二维 numpy 数组不会出错

标签 python numpy indexing

当我在 numpy 中创建一个一维数组并使用一个字符串(包含数字)对其进行索引时,我得到了预期的错误:

>>> import numpy as np
>>> a = np.arange(15)
>>> a['10']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: field named 10 not found.

但是,当我创建一个二维数组并使用两个字符串进行索引时,它没有报错并返回元素,就好像字符串首先被转换为整数一样

>>> b = np.arange(15).reshape(3,5)
>>> b
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> b[1, 2]
7
>>> b['1', '2']
7

这是怎么回事?为什么我在二维情况下不会出错?

最佳答案

免责声明 -- 这个答案肯定是不完整的

我认为您看到的是 fancy sequence indexing 的结果.由于字符串实际上是序列,您一次获取字符串的一个字符的值并将它们转换为“intp”对象(大概只使用 python 的 int 函数)-- 然后为您提供数组索引。

这也解释了 1D 情况:

class Foo(object):
    def __getitem__(self,idx):
        print idx

a = Foo()
a[12]
a[12,12]

请注意,在第二种情况下传递的是一个元组,而在第一种情况下传递的是一个整数。


这个测试证明了我仍然不明白的部分:

import numpy as np
a = np.arange(156).reshape(13,12)
print a[12,3] == a['12',3]   #True -- I would have thought False for this one...
print a['12',3] == a[('1','2'),3]  #False -- I would have guessed True for this..
assert( a[tuple('12'),3] == a[(1,2),3] )  #This passes, as expected

请随时尝试在评论中向我解释这一点。 :) 差异可能是 numpy 在转换为 intp 对象序列时故意不理会字符串,以便更顺利地处理记录数组...

关于python - 使用包含数字的字符串进行索引时,二维 numpy 数组不会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13158452/

相关文章:

python - numpy 中的数组索引

python - matplotlib 中的 "Sticky notes"

sql - SQL Server 表索引问题

mysql - 在 MySQL 数据库中保持 TEXT 字段唯一的最佳方法

python - 过滤器无效 : 'markdown' django-markdown-deux

python - 关于正则表达式

python - 如何在 PyQtWebEngine 中打开目标为 ="_blank"的超链接?

python - Numpy sum(Numpy 1.15.4,与 MKL 链接)

sql-server - 如何从 SQL Server 数据库中删除所有数据库索引

theta模型的python实现(theta方法)