


Detailed explanation of the usage of where() function in Python
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 ''' 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)
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!

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

The article discusses unit tests in Python, their benefits, and how to write them effectively. It highlights tools like unittest and pytest for testing.

Article discusses access specifiers in Python, which use naming conventions to indicate visibility of class members, rather than strict enforcement.

Article discusses Python's \_\_init\_\_() method and self's role in initializing object attributes. Other class methods and inheritance's impact on \_\_init\_\_() are also covered.

The article discusses the differences between @classmethod, @staticmethod, and instance methods in Python, detailing their properties, use cases, and benefits. It explains how to choose the right method type based on the required functionality and da

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
