0

Considering the following dataset extracted using numpy.genfromtxt():

    data[0:3]
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)], 
      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')])

I am trying to retrieve the letters from the first 2 arrays using the following code but it's giving the first complete array instead of the first element from each array.

data[:2][0]
0

2 Answers 2

1

The issue is that the contents of the array are tuples. So, when you ask for data[:2][0] it returns the 0'th item in a list of tuples, and not the 0th item of each tuple. Use the following snippet:

output = []
for i in range(2):
    output += data[:2][i][0]

Hope I helped.

Sign up to request clarification or add additional context in comments.

1 Comment

They display like tuples, but are actually records of a structured array. Your output will be a list like [84, 73, 68]. Those are the numerical byte values of the bytestrings, [b'T', b'I', b'D'].
0

This is a structured array, 1d with many fields. Fields are accessed by name, not 'column' number:

In [618]: data
Out[618]: 
array([(b'T', 2,  8, 3, 5, 1,  8, 13, 0, 6,  6, 10, 8, 0, 8, 0,  8),
       (b'I', 5, 12, 3, 7, 2, 10,  5, 5, 4, 13,  3, 9, 2, 8, 4, 10),
       (b'D', 4, 11, 6, 8, 6, 10,  6, 2, 6, 10,  3, 7, 3, 7, 3,  9)],
      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')])

One element or record (displays like a tuple)

In [619]: data[0]
Out[619]: (b'T', 2, 8, 3, 5, 1, 8, 13, 0, 6, 6, 10, 8, 0, 8, 0, 8)

One field, an array:

In [620]: data['f0']
Out[620]: 
array([b'T', b'I', b'D'],
      dtype='|S1')

Several fields, returning another structured array (as illustrated in your next question, Access range of elements from an array Python)

In [621]: data[['f1','f2']]
Out[621]: 
array([(2,  8), (5, 12), (4, 11)],
      dtype=[('f1', '<i8'), ('f2', '<i8')])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.