[英]Python: Filter rows in data frame when multiple rows meet a unique condition
[英]Print rows that meet multiple if statements in Python
目的
我想打印滿足特定條件的文件主文件的整行。
問題
之前,我有
if rank <= 50 and price <= 10000:
代替
if np.any(rank <= 50) and np.any(price <= 10000):
但我收到錯誤: ValueError: 具有多個元素的數組的真值不明確。 使用 a.any() 或 a.all()
而且我不相信 a.any() 的使用是合適的,因為它會返回一個布爾值。 我也很難理解我如何只能打印滿足這些條件的主行。
在此先感謝您的幫助和解釋!
這是數據:
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")
正如對您的問題的評論一樣,使用布爾數組和np.logical_and
的組合來索引滿足您的條件的行。
import numpy as np
master = np.loadtxt('master.txt', delimiter=',')
print(master[np.logical_and(master[:, 0] <= 50, master[:, 2] <= 10000)])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.