2

I would like to create an array which is filled with identical tuples initially, specifically with tuples of NaN. E.g.,

array([[(nan, nan), (nan, nan)],
       [(nan, nan), (nan, nan)],
       [(nan, nan), (nan, nan)]], dtype=object)

However, when using the array initialisations listed e.g. here with an iterable value as value for filling in array, python apparently tries to reshape that iterable into the new array rather than fill it with it:

np.full([3,2],(np.nan,np.nan,np.nan),dtype=tuple)
#ValueError: could not broadcast input array from shape (3) into shape (3,2)

np.fill does not work either, it requires a scalar.

Is it only possible to fill the array item by item?

3
  • Provide provide code in the question, instead of providing link, or provide an explicit link to the code itself Commented Sep 9, 2020 at 14:23
  • What do you actually intend to do with those tuples? The accepted answer didn't actually fill the array with tuples. It made a structured array, which displays elements as tuples. And when dealing with object arrays as you tried, there's a difference between 'identical tuples' and the 'same tuple'. Commented Sep 9, 2020 at 15:57
  • @hpaulj it is an initialisation for an array whose elements will contain maximum floating point value within an array of tuples of the same shape. So yes, it's identical, if I understand correctly and 'same' would mean reference to one single tuple. Commented Sep 10, 2020 at 6:16

1 Answer 1

3

You can, with the correct dtype. With 'f,f' you can initialise the array with tuples of floats; see Data type objects (dtype) for more.

np.full((3,2), np.nan, dtype='f,f')

array([[(nan, nan), (nan, nan)],
       [(nan, nan), (nan, nan)],
       [(nan, nan), (nan, nan)]], dtype=[('f0', '<f4'), ('f1', '<f4')])
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - it's probably a different issue, but then elements within the tuples are not np.nan anymore, A[0,0][0] is np.nan returns false? Although math.isnan returns true.
that is because np.nan!=np.nan (try it). You need to use np.isnan(A[0,0][0]) @joce
Thanks - I had seen syntax is np.nan elsewhere, but I realise now how wrong it is - means "is the same memory object".

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.