1

I would like the code to return "fail" statement if the numpy array contains value that is not 0 or 10. Checking 2nd and 3rd column, as long as there is one value that doesn't satisfy the criteria, the code returns "fail". My code always return pass.

data file has the format:

0 0 0 0
1 0 0 0
2 0 0 0
3 0 0 0
4 50 10 0
5 10 10 0
6 10 10 0    
7 10 10 0

data = np.loadtxt('datafile.txt')
x1, x2 = data[:,1], data[:2]

if (x1.any != 0 or x1.any !=10):
    x1label = 'fail'
else:
    x1label = 'pass'

if (x2.any !=0 or x2.any !=10):
    x2label = 'fail'
else:
    x2label = 'pass'

if (x1label == 'fail') or (x2label == 'fail'):
    label = 'fail'
else:
    label = 'pass'

2 Answers 2

1

You use any before comparison, which mean you compare bool with int.

data = np.loadtxt('datafile.txt')
x1, x2 = data[:,1], data[:2]

if np.any(x1 != 0) or np.any(x1 !=10):
    x1label = 'fail'
else:
    x1label = 'pass'

if np.any(x2 !=0) or np.any(x2 !=10):
    x2label = 'fail'
else:
    x2label = 'pass'

if (x1label == 'fail') or (x2label == 'fail'):
    label = 'fail'
else:
    label = 'pass'
Sign up to request clarification or add additional context in comments.

5 Comments

If i don't use any, it gets the following error ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
@hamster you can use np.any, why not.
Ah. My mistake. I didn't see you have moved any before the comparison. It is now returning fail which is correct. But when i put into a loop, reading the second file, which should have given me "pass" , it isn't.
Instead of just 'datafile.txt', i now put it in a loop to read in several data files one-by-one and do the same evaluation. I am expecting the first to return fail, and the second to return pass. I am not sure how to write an example code under comment.
I think i know why doing the loop doesn't work. As a test, i change "50" in the data file to "10", your code should have returned "pass" but it isn't.
0

A different approach, which i find it works.

    import numpy as np

    a_file = open('datafile.txt', 'r')
    LINES = a_file.readlines()
    a_file.close()

    for i in range(len(LINES)):
        line = LINES[i]
        TOKS = line.split()
        x1 = TOKS[1]
        x2 = TOKS[2]
        if (x1 != '0' and x1 != '10'):
            x1label = 'fail'
            break        
        else:
            x1label = 'pass'

        if (x2 != '0' and x2 != '10'):
            x2label = 'fail'
            break        
        else:
            x2label = 'pass'

    if (x1label == 'fail') or (x2label == 'fail'):
            label = 'fail'
    else:
            label = 'pass'

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.