3

The following demonstrates the problem:

import io
import numpy as np

a = np.loadtxt(io.StringIO("val1 val2\nval3 val4"), \
               dtype=np.dtype([("col1", "S10"), ("col2", "S10")]))
print("looks weired: %s"%(a["col1"][0]))
assert(a["col1"][0] == "val1")

I don't understand how I should compare the strings. On my system (numpy 1.6.2, python 3.2.2) the output looks like this:

>>> 
looks weired: b'val1'
Traceback (most recent call last):
  File "D:/..../bug_sample.py", line 7, in <module>
    assert(a["col1"][0] == "val1")
AssertionError

1 Answer 1

4

This is not numpy-related:

>>> b"asd" == "asd"
False

In Python 3 bytes objects don't compare equal to strings. So either:

  • compare against b"val1" instead of "val1" so that the types match,
  • decode the bytes object into a string (like .decode('utf-8') and compare with "val1".
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Kos, but why is the value returned as a byte array if it is declared "S10"? I would expect it to be a np.str. The behavoir of numpy is not intuitive.
That depends on your intuition. :-) Maybe they just didn't want the typestrings to change meaning in Python 3. See also docs.scipy.org/doc/numpy/reference/…
Kos, I am new to py3k so maybe I oversee something fundamental... but the result of this simply looks wrong: a = np.loadtxt(io.StringIO("val1 val2\nval3 val4"), dtype=np.dtype([("col1", np.str, 4), ("col2", "S4")])) print(a)

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.