python 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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值