第一种用法

np.where(conditions,x,y)

if (condituons成立):

  数组变x

else:

  数组变y

import numpy as np
'''
x = np.random.randn(4,4)
print(np.where(x>0,2,-2))
#试试效果
xarr = np.array([1.1,1.2,1.3,1.4,1.5])
yarr = np.array([2.1,2.2,2.3,2.4,2.5])
zarr = np.array([True,False,True,True,False])
result = [(x if c else y)
          for x,y,c in zip(xarr,yarr,zarr)]
print(result)

#where()函数处理就相当于上面那种方案

result = np.where(zarr,xarr,yarr)
print(result)

'''
#发现个有趣的东西
# #处理2组数组
# #True and True = 0
# #True and False = 1
# #False and True = 2
# #False and False = 3

cond2 = np.array([True,False,True,False])
cond1 = np.array([True,True,False,False])
#第一种处理 太长太丑
result = []
for i in range(4):
    if (cond1[i] & cond2[i]):   result.append(0);
    elif (cond1[i]):    result.append(1);
    elif (cond2[i]):    result.append(2);
    else :  result.append(3);
print(result)
#第二种 直接where() 很快很方便
result = np.where(cond1 & cond2,0,np.where(cond1,1,np.where(cond2,2,3)))
print(result)
#第三种 更简便(好像这跟where()函数半毛钱的关系都没有
result = 1*(cond1 & -cond2)+2*(cond2 & -cond1)+3*(-(cond1 | cond2))  (没想到还可以这么表达吧)
print(result)
  
View Code

相关文章:

  • 2021-12-10
  • 2021-04-30
  • 2021-07-20
  • 2021-04-16
  • 2021-06-14
  • 2021-11-01
猜你喜欢
  • 2021-08-11
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
  • 2022-12-23
  • 2021-08-19
  • 2021-05-24
相关资源
相似解决方案