· python python3

Python 3: TypeError: unsupported format string passed to numpy.ndarray.*format*

This post explains how to work around a change in how Python string formatting works for numpy arrays between Python 2 and Python 3.

I’ve been going through Kevin Markham's scikit-learn Jupyter notebooks and ran into a problem on the Cross Validation one, which was throwing this error when attempting to print the KFold example:

Iteration                   Training set observations                   Testing set observations
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-007cbab507e3> in <module>()
      6 print('{} {:^61} {}'.format('Iteration', 'Training set observations', 'Testing set observations'))
      7 for iteration, data in enumerate(kf, start=1):
----> 8     print('{0:^9} {1} {2:^25}'.format(iteration, data[0], data[1]))

TypeError: unsupported format string passed to numpy.ndarray.__format__

We can reproduce this easily:

>>> import numpy as np
>>> "{:9}".format(np.array([1,2,3]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to numpy.ndarray.__format__

What about if we use Python 2?

>>> "{:9}".format(np.array([1,2,3]))
'[1 2 3]  '

Hmmm, must be a change between the Python versions.

We can work around it by coercing our numpy array to a string:

>>> "{:9}".format(str(np.array([1,2,3])))
'[1 2 3]  '
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket