Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have some data files that contain boolean output from Fortran code:

write(23,'(L2)') data

therefore, a portion of the file will look like this:

F F T F ...

I would like to read this file in Python with numpy.asarray() function, because it is easy to convert data this way, e.g.:

data = asarray(f.readline().split(),'bool')

However, no matter what data it is, Python always returns an array with all 'True's.

I have also tried to write as 'False False True False ...' or '0 0 1 0 ...', and they both did not work.

I would like to know if there is a way to use asarray() to achieve this? or any other suggestions that can convert boolean data without using loops?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

One way would be to do a tiny bit more processing on each of the strings of the input file to get the results you're expecting:

with open('input.dat') as handle:
    data = asarray([[x == 'T' for x in line.strip().split()]
                    for line in handle],
                   dtype=bool)

Here I'm reading through each line in the file handle, and then for each field on the line, I compare it to the string 'T'. This will give a boolean result, which can be stored in your data array as expected.

The problem with the code you presented is that Python is doing its best to convert the values that you give it to Booleans; however, in Python non-empty strings evaluate to True when cast as Booleans: bool('T') == bool('F') == bool('0') == bool('1') == True.

share|improve this answer
    
This is what I need exactly, and from your answer I also learned implicit for loops which I had not used much but always wanted to. –  warriormole Aug 23 '13 at 2:04

If you can read in the data as an array of "T" and "F" strings then you could do the following:

>>> a = np.array(["T", "F", "T"])
>>> a == "T"
array([ True, False,  True], dtype=bool)
share|improve this answer
    
This is also a great answer, and would probably be much faster than my solution. –  lmjohns3 Aug 22 '13 at 18:01
    
Agree with Imjohns3, basically it is this " array=='T' " syntax that I did not know before. –  warriormole Aug 23 '13 at 2:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.