1

This NumPy 2.2.6 script:

import numpy as np 

a = np.arange(24).reshape(2, 2, 2, 3)
idx = np.unravel_index(np.argmax(a, axis=None), a.shape)
print(idx)

will print:

(np.int64(1), np.int64(1), np.int64(1), np.int64(2))

which is hard to read. What is a simple way to print idx as (1, 1, 1, 2)? I'm looking for something better than print(np.array(idx)) workaround.

6
  • 3
    tuple(i.item() for i in idx); you're printing a literal tuple (try type(idx)) Commented Sep 1 at 6:47
  • What version numpy are you using? Commented Sep 1 at 7:02
  • @Daweo There has been a change in the scalar representation as of Numpy 2.0.0 (see release notes): As per NEP 51, the scalar representation has been updated to include the type information to avoid confusion with Python scalars. Commented Sep 1 at 7:17
  • @Daweo NumPy 2.2.6 Commented Sep 1 at 7:24
  • Would printing 1 1 1 2 be ok, too? Commented Sep 1 at 12:14

2 Answers 2

4

This is the new way to represent numpy scalars since version 2.

You can revert to the old printing style with the legacy parameter of numpy.set_printoptions:

np.set_printoptions(legacy='1.25')

print(idx)
# (1, 1, 1, 2)

And to switch back to the new style: np.set_printoptions(legacy=False).

Alternatively, explicitly convert to python integers or strings:

print(tuple(int(i) for i in idx))  # or: print(tuple(map(int, idx)))
# (1, 1, 1, 2)
Sign up to request clarification or add additional context in comments.

Comments

3

Since you said printing 1 1 1 2 would be ok, too:

print(*idx)

That prints each element's str instead of its repr.

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.