代码之家  ›  专栏  ›  技术社区  ›  Jason S

如何访问numpy重新数组的字段#k?

  •  3
  • Jason S  · 技术社区  · 12 年前

    我可以创建一个重新数组并按名称访问其成员:

    import numpy as np
    
    n = 20
    x = np.recarray((n,), dtype=[('x',int),('y',float),('label',object)])
    x.x[:] = range(n)
    x.y[:] = np.arange(n)*0.08
    x.label[:] =  ['%d bottles of beer on the wall' % i for i in range(n)]
    

    并且我可以通过行索引访问数据,或者对行进行迭代:

    >>> print x[3]
    (3, 0.24, '3 bottles of beer on the wall')
    

    但是,我如何迭代字段或获取 k 重新排列中的第个字段?

    1 回复  |  直到 12 年前
        1
  •  3
  •   JaminSore    12 年前

    recarray 我们有一个 field() 方法。用你的例子。。。

    >>> x.field(2)
    ... array(['0 bottles of beer on the wall', '1 bottles of beer on the wall',
           '2 bottles of beer on the wall', '3 bottles of beer on the wall',
           '4 bottles of beer on the wall', '5 bottles of beer on the wall',
           '6 bottles of beer on the wall', '7 bottles of beer on the wall',
           '8 bottles of beer on the wall', '9 bottles of beer on the wall',
           '10 bottles of beer on the wall', '11 bottles of beer on the wall',
           '12 bottles of beer on the wall', '13 bottles of beer on the wall',
           '14 bottles of beer on the wall', '15 bottles of beer on the wall',
           '16 bottles of beer on the wall', '17 bottles of beer on the wall',
           '18 bottles of beer on the wall', '19 bottles of beer on the wall'], dtype=object)
    
    推荐文章