NumPy argmax and structured array error: expected a readable buffer object

730 views Asked by At

I got the following error while using NumPy argmax method. Could some one help me to understand what happened:

import numpy as np
b = np.zeros(1, dtype={'names':['a','b'], 'formats': ['i4']*2})
b.argmax()

The error is

TypeError: expected a readable buffer object

While the following runs without a problem:

a = np.zeros(3)
a.argmax()

It seems the error dues to the structured array. But could you anyone help to explain the reason?

1

There are 1 answers

0
hpaulj On

Your b is:

array([(0, 0)], dtype=[('a', '<i4'), ('b', '<i4')])

I get a different error message with argmax:

TypeError: Cannot cast array data from dtype([('a', '<i4'), ('b', '<i4')]) to dtype('V8') according to the rule 'safe'

But this works:

In [88]: b['a'].argmax()
Out[88]: 0

Generally you can't do math operations across the fields of a structured array. You can operate within each field (if it is numeric). Since the fields could be a mix of numbers, strings and other objects, so there's been no effort to handle special cases where such operations might make sense.

If you really must to operations across the fields, try a different view, eg:

In [94]: b.view('<i4').argmax()
Out[94]: 0