Python vs Matlab—— find 与 np where

1. matlab中的find函数

将数组中的偶数值返回:

x = randperm(100, 10)
x(mod(x, 2) == 0)
  • 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

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

3. python numpy:np.where

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

>>a = np.array(a)
>>a
array([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

注意,这种情况下,也即 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

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

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://www.cnblogs.com/captainbed

猜你喜欢

转载自www.cnblogs.com/siwnhwxh/p/10181090.html