0

I am trying to read a file and create an array from it. The file is as follows:

1 0
0 1

The code is:

line = file.read()
array = np.fromstring(line.strip(),dtype = bool, sep = " ")
array.resize(2,2)
print array

The output is:

[[ True False]
 [False  True]]

but there is always an extra space before 'True.' Does anyone know how to remove it?

4
  • 2
    That's just the printing style. Commented Apr 17, 2014 at 4:05
  • NumPy does that so things line up nicely. If it didn't, it would have to left-align the output and put the extra spaces at the end, or it would have to simply abandon trying to line things up at all. Commented Apr 17, 2014 at 4:08
  • I was considering the extra spaces in the second row because I was wondering if the spaces would cause an error when I processed the array later, but it makes sense that NumPy does that for formatting. Commented Apr 17, 2014 at 4:09
  • 1
    The spaces won't cause errors. However, note that print isn't a good way to serialize an array. Try print numpy.zeros([1001]) to see why. Commented Apr 17, 2014 at 4:11

1 Answer 1

1

You have reproduced the output incorrectly:

In [8]: print np.fromstring(line,sep = " ").reshape(2,2).astype("bool")
[[ True False]
 [False  True]]

The values are right-aligned for each column.

As an aside, the more numpythonic way of doing this is:

In [9]: np.genfromtxt("<name of text file>").astype("bool")
Out[9]: 
array([[ True, False],
       [False,  True]], dtype=bool)
Sign up to request clarification or add additional context in comments.

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.