从数组Python访问元素范围

时间:2017-09-24 11:06:06

标签: python numpy

考虑以下数据集:

>>> data[:10]
array([('T',  2,  8,  3, 5, 1,  8, 13, 0, 6,  6, 10,  8, 0,  8, 0,  8),
       ('I',  5, 12,  3, 7, 2, 10,  5, 5, 4, 13,  3,  9, 2,  8, 4, 10),
       ('D',  4, 11,  6, 8, 6, 10,  6, 2, 6, 10,  3,  7, 3,  7, 3,  9),
       ('N',  7, 11,  6, 6, 3,  5,  9, 4, 6,  4,  4, 10, 6, 10, 2,  8),
       ('G',  2,  1,  3, 1, 1,  8,  6, 6, 6,  6,  5,  9, 1,  7, 5, 10),
       ('S',  4, 11,  5, 8, 3,  8,  8, 6, 9,  5,  6,  6, 0,  8, 9,  7),
       ('B',  4,  2,  5, 4, 4,  8,  7, 6, 6,  7,  6,  6, 2,  8, 7, 10),
       ('A',  1,  1,  3, 2, 1,  8,  2, 2, 2,  8,  2,  8, 1,  6, 2,  7),
       ('J',  2,  2,  4, 4, 2, 10,  6, 2, 6, 12,  4,  8, 1,  6, 1,  7),
       ('M', 11, 15, 13, 9, 7, 13,  2, 6, 2, 12,  1,  9, 8,  1, 1,  8)], 
      dtype=[('f0', 'S1'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<i8'), ('f5', '<i8'), ('f6', '<i8'), ('f7', '<i8'), ('f8', '<i8'), ('f9', '<i8'), ('f10', '<i8'), ('f11', '<i8'), ('f12', '<i8'), ('f13', '<i8'), ('f14', '<i8'), ('f15', '<i8'), ('f16', '<i8')])

如何从每个数组中访问除第一个元素之外的所有元素。我使用以下代码但无济于事。

>>> nd.array([[x[1:] for x in data[:10]])

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用dtype.names属性访问所有列名称,然后对其进行切片:

>>> data[list(data.dtype.names[1:])]
array([( 2,  8,  3, 5, 1,  8, 13, 0, 6,  6, 10,  8, 0,  8, 0,  8),
       ( 5, 12,  3, 7, 2, 10,  5, 5, 4, 13,  3,  9, 2,  8, 4, 10),
       ( 4, 11,  6, 8, 6, 10,  6, 2, 6, 10,  3,  7, 3,  7, 3,  9),
       ( 7, 11,  6, 6, 3,  5,  9, 4, 6,  4,  4, 10, 6, 10, 2,  8),
       ( 2,  1,  3, 1, 1,  8,  6, 6, 6,  6,  5,  9, 1,  7, 5, 10),
       ( 4, 11,  5, 8, 3,  8,  8, 6, 9,  5,  6,  6, 0,  8, 9,  7),
       ( 4,  2,  5, 4, 4,  8,  7, 6, 6,  7,  6,  6, 2,  8, 7, 10),
       ( 1,  1,  3, 2, 1,  8,  2, 2, 2,  8,  2,  8, 1,  6, 2,  7),
       ( 2,  2,  4, 4, 2, 10,  6, 2, 6, 12,  4,  8, 1,  6, 1,  7),
       (11, 15, 13, 9, 7, 13,  2, 6, 2, 12,  1,  9, 8,  1, 1,  8)],
      dtype=[('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<i8'), 
             ('f5', '<i8'), ('f6', '<i8'), ('f7', '<i8'), ('f8', '<i8'),
             ('f9', '<i8'), ('f10', '<i8'), ('f11', '<i8'), ('f12', '<i8'), 
             ('f13', '<i8'), ('f14', '<i8'), ('f15', '<i8'), ('f16', '<i8')])