Reputation: 3986
I am new to Python and I am trying to write a simple print function but I am getting a strange error. This is my code:
#! /usr/bin/env python3.2
import numpy as np
a=np.arange(1,10,1)
print(a)
for i in a:
print(i)
print(type(i))
print("{0:<12g}".format(i))
The output is:
[1 2 3 4 5 6 7 8 9]
1
<class 'numpy.int64'>
Traceback (most recent call last):
File "./test.py", line 9, in <module>
print("{0:<12g}".format(i))
ValueError: Unknown format code 'g' for object of type 'str'
Why does print take the "numpy.int64" as a string? I have to add that it works perfectly for a normal list: (e.g. [1,2,3,4]) I would be most grateful to any ideas on this issue, thanks ;-).
Upvotes: 2
Views: 14591
Reputation: 43
If you stumble upon this error while trying to use seaborn.heatmap with annotations such as:
import seaborn as sns
import numpy as np
data = pd.DataFrame(np.random.rand(3,4))
annot = np.where(data > 0, 'Yes', 'No')
ax = sns.heatmap(data, annot=annot)
ValueError: Unknown format code 'g' for object of type 'numpy.str_'
You can make it work by adding fmt=''
as argument to sns.heatmap such as:
ax = sns.heatmap(data, annot=annot, fmt='')
It should do the trick.
Upvotes: 1
Reputation: 174624
This is a known bug and should be fixed in version 2.0. In the interim, you can use the old syntax %f
that works.
Upvotes: 2
Reputation: 12747
Someone will be able to give you a more in-depth answer, but what I think is happening here is that you're using "{0:<12g}".format(i)
which uses special formatting. If you'd try "\{{0}:<12g\}".format(i)
you'd probably get better results. Using the slashes there escapes the {}
's which is what is giving you the error.
Upvotes: 0