【问题标题】:Print rows that meet multiple if statements in Python在 Python 中打印满足多个 if 语句的行
【发布时间】:2020-01-12 17:44:26
【问题描述】:

目标

我想打印文件ma​​ster中满足特定条件的整行。

问题

以前,我有

if rank <= 50 and price <= 10000:

而不是

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

但我得到了错误: ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

我不相信使用 a.any() 是合适的,因为它会返回一个布尔值。我也很难理解我如何只能打印满足这些条件的 ma​​ster 行。

提前感谢您的帮助和解释!

这是数据:

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")

【问题讨论】:

标签: python numpy if-statement


【解决方案1】:

正如您问题的 cmets 中一样,使用布尔数组和 np.logical_and 的组合来索引满足您条件的行。

import numpy as np

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

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

【讨论】:

  • 如何使打印显示为整数而不是科学计数法?我试过np.set_printoptions(precision=int) 但我收到错误 TypeError: '
  • @Joehat Setting np.set_printoptions(suppress=True) 将抑制科学记数法。请注意,如果您想使用precision 参数,您必须设置一个实际的整数,例如np.set_printoptions(precision=3)
最近更新 更多