根据多个值条件从数组中提取值

时间:2020-04-23 19:05:09

标签: python arrays numpy

我有一个浮点数数组。我想根据多种条件选择其值:

import numpy as np
stamps = np.linspace(1., 100., 1e3)  
selected_stamps = stamps[((stamps > 2.)& (stamps < 10) & (stamps > 20.)& (stamps < 31) & (stamps > 80.)& (stamps < 95) )] # select only values within 2-10, 20-31, 80-95

我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果您仅使用and运算符,则会得到一个空集合。您有3个范围,因此在每个范围之间都需要一个or运算符:

selected_stamps = stamps[(
    ((stamps > 2.) & (stamps < 10)) | 
    ((stamps > 20.)& (stamps < 31)) | 
    ((stamps > 80.)& (stamps < 95)) )]