find 和 np.where

来源:互联网 发布:qq三国79js 79xs 编辑:程序博客网 时间:2024/06/03 15:58

1. matlab中的find函数

将数组中的偶数值返回:

x = randperm(100, 10)x(mod(x, 2) == 0)
  • 1
  • 2
  • 1
  • 2

matlab中find的函数的强大之处在于其能返回下标,且视返回参数的个数,返回以列全排序的一维下标(返回参数的个数为1),返回行列索引的二维坐标(返回参数的个数为2):

>>A = [1, 2, 3; 1, 2, 3; 1, 2, 3]>>idx = find(A > 2)            % idx = 7 8 9   >>A(idx)    % 3 3 3% 当然也可以更简洁地索引符合某一条件(predicate,断言)的元素>>A(A>2)>>[rows, cols] = find(A > 2)        rows = 1 2 3        cols = 3 3 3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2. python:遍历+判断

>>a = [1, 2, 3, 1, 2, 3, 1, 2, 3]>>idx = [idx for (idx, val) in enumerate(a) if val > 2]>>idx[2, 5, 8]>>vals = [val for (idx, vals) in enumerate(a) if val > 2][3, 3, 3]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3. python numpy:np.where

Python或者numpy中能够返回符合某一条件的下标的函数是np.where(),不过np.where()并不接受list类型的参数,可见np.where()既可以接收三个参数,用于三目运算,也可接收一个参数,返回符合条件的下标。

>>a = np.array(a)>>aarray([1, 2, 3, 1, 2, 3, 1, 2, 3])>>idx = np.where(a > 2)>>idx(array([2, 5, 8], dtype=int32),)>>a[idx]               # 这种做法并不推荐array([3, 3, 3])        >>a[a>2]               # 推荐的做法array([3, 3, 3])    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

注意,这种情况下,也即 np.where() 用于返回断言成立时的索引,返回值的形式为 arrays of tuple,由 np.array 构成的 tuple,一般 tuple 的 len 为2(当判断的对象是多维数组时),哪怕是一维数组返回的仍是 tuple,此时tuple 的 len 为 1;

  • np.where()[0] 表示行的索引,
  • np.where()[1] 则表示列的索引

np.where()用于三目运算的情况:

>>y = np.array([1, 2, 3, 4, 5, 6])  # 将奇数转换为偶数,偶数转换为奇数>>y = np.where(y%2 == 0, y+1, y-1)>>y array([0, 3, 2, 5, 4, 7])
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

4. 处理NaN(not a number)

将nan所在的列非nan的均值赋给这些nan值

>>A = np.array([[1, 2, 3, 4], [5, 6, np.nan, 8], [9, 10, 11, np.nan]])>>idx = np.where(np.isnan(A))>>idx(array([1, 2], dtype=int32), array([2, 3], dtype=int32))for i in idx:    A[i[0], i[1]] = A[~np.isnan(A[:, i[1]]), i[1]].mean()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
原创粉丝点击