numpy根据条件取值

示例代码:

import numpy as np

my_np1 = np.arange(18).reshape(3,6)
print(my_np1[my_np1<10])    #打印[0 1 2 3 4 5 6 7 8 9]
print(my_np1[(my_np1>2)&(my_np1<6)])    # 与:&  打印:[3 4 5]
print(my_np1[(my_np1<2)|(my_np1>6)])   # 或:|  打印:[ 0  1  7  8  9 10 11 12 13 14 15 16 17]
print(my_np1[~(my_np1>6)])        # 非:~  打印:[0 1 2 3 4 5 6]

# 三目运算( np.where(condition, x, y)满足条件(condition),输出x,不满足输出y。))
my_np2 = np.arange(18).reshape(3,6)
my_np2_new = np.where(my_np2>10,1,0)
print(my_np2_new)
'''
打印:
[[0 0 0 0 0 0]
 [0 0 0 0 0 1]
 [1 1 1 1 1 1]]
'''

猜你喜欢

转载自blog.csdn.net/caoxinjian423/article/details/112073866