简体   繁体   中英

Print rows that meet multiple if statements in Python

AIM

I would like to print the entire rows of the file master that meet certain conditions.

PROBLEM

Before, I had

if rank <= 50 and price <= 10000:

instead of

if np.any(rank <= 50) and np.any(price <= 10000):

but I was getting the error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

and I don't believe the use of a.any() is appropriate as it would return a boolean. I'm also struggling to understand how I can only print the rows of master that meet those conditions.

Thanks in advance for your help and explanations!

Here's the data:

1,11,10950
2,14,11000
3,15,10500
5,18,9750
6,19,9045
7,19,9945
8,19,9945
9,20,9250
10,21,7850
11,22,10620
12,26,9700
13,28,9300
14,29,9000
15,50,7170
16,53,9200
17,58,9085
18,63,8570
19,67,7920
20,75,6900
21,86,6085
23,130,5750
import numpy as np

master = np.loadtxt('master.txt', delimiter=',')

uni = master[:, 0]
rank = master[:, 1]
price = master[:, 2]


if np.any(rank <= 50) and np.any(price <= 10000):
    print("Print rows that meet conditions")

As in the comments to your questions, use a combination of boolean arrays and np.logical_and to index the rows which satisfy your conditions.

import numpy as np

master = np.loadtxt('master.txt', delimiter=',')

print(master[np.logical_and(master[:, 0] <= 50, master[:, 2] <= 10000)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM