Home  >  Article  >  Backend Development  >  Detailed explanation of the usage of where() function in Python

Detailed explanation of the usage of where() function in Python

小云云
小云云Original
2018-03-29 13:09:0112177browse

This article mainly introduces you to the detailed usage of the where() function in Python. The editor thinks it is quite good. Now I will share it with you and give you a reference. I hope it can help you.

Usage of where()

First of all, let me emphasize that the where() function only returns different values ​​for different inputs.

1 When the array is a one-dimensional array, the returned value is a one-dimensional index, so there is only one set of index arrays

2 When the array is a two-dimensional array, the array value that meets the conditions What is returned is the position index of the value, so there will be two sets of index arrays to represent the position of the value

For example,


>>>b=np.arange(10)
>>>b
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>np.where(b>5)
 (array([6, 7, 8, 9], dtype=int64),)

>>>a=np.reshape(np.arange(20),(4,5))
>>>a 
array([[ 0, 1, 2, 3, 4],
    [ 5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19]])
>>>np.where(a>10)
(array([2, 2, 2, 2, 3, 3, 3, 3, 3], dtype=int64),
 array([1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=int64))

for the numpy standard library An introduction to the explanation here:


numpy.where(condition[, x, y])

Based on the condition, the return value comes from x or y.

If.

Parameters:

condition: array, bool value

When True, yield x, otherwise yield y.

x, y: array_like, optional

The shapes of x and y must be the same. When the value in condition is true, the value corresponding to x is returned. If false, the value of y is returned.

Return value:

out : ndarray or tuple of ndarrays

①If the parameters include condition, x and y, the shapes of their three parameters are the same. Then, when the value in condition is true, the value corresponding to x is returned, and if false, y is returned.

② If the parameter is only condition, the return value is the position index where the element value in condition is true. It is returned in the form of a tuple. The element of the tuple is an ndarray array, indicating the index of the position.


>>> np.where([[True, False], [True, True]],
...     [[1, 2], [3, 4]],
...     [[9, 8], [7, 6]])
array([[1, 8],
    [3, 4]])
>>>
>>> np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))
>>>
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 3.0 )]        # Note: result is 1D.
array([ 4., 5., 6., 7., 8.])
>>> np.where(x < 5, x, -1)        # Note: broadcasting.
array([[ 0., 1., 2.],
    [ 3., 4., -1.],
    [-1., -1., -1.]])
Find the indices of elements of x that are in goodvalues.

>>>
>>> goodvalues = [3, 4, 7]
>>> ix = np.in1d(x.ravel(), goodvalues).reshape(x.shape)
>>> ix
array([[False, False, False],
    [ True, True, False],
    [False, True, False]], dtype=bool)
>>> np.where(ix)
(array([1, 1, 2]), array([0, 1, 1]))

Sample code for two methods

First usage

np.where(conditions,x,y)

if (conditions are established):

Array becomes x

else:

Array Change y


import numpy as np
&#39;&#39;&#39;
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)

&#39;&#39;&#39;
#发现个有趣的东西
# #处理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)

The second usage

where(conditions)

is equivalent to giving the subscript of the array


x = np.arange(16)
print(x[np.where(x>5)])
#输出:(array([ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], dtype=int64),)

x = np.arange(16).reshape(-1,4)
print(np.where(x>5))

#(array([1, 1, 2, 2, 2, 2, 3, 3, 3, 3], dtype=int64), array([2, 3, 0, 1, 2, 3, 0, 1, 2, 3], dtype=int64))
#注意这里是坐标是前面的一维的坐标,后面是二维的坐标


ix = np.array([[False, False, False],
    [ True, True, False],
    [False, True, False]], dtype=bool)
print(np.where(ix))
#输出:(array([1, 1, 2], dtype=int64), array([0, 1, 1], dtype=int64))

The above is the detailed content of Detailed explanation of the usage of where() function in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn