


Implement ndarray array in numpy to return index method that meets specific conditions
The following is an article in numpy that implements an ndarray array to return an index that meets specific conditions. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
In the ndarray type of numpy, there seems to be no method to directly return a specific index. I only found the where function, but the where function is very useful for finding the index corresponding to a specific value. For Returning an index of values within a certain range is not very efficient, at least I don't understand how to do it. Let’s first talk about the usage of where function.
(1) Usage scenarios of where function:
For example, now I generated an array:
import numpy as np arr=np.array([1,1,1,134,45,3,46,45,65,3,23424,234,12,12,3,546,1,2])
Now arr is an ndarray type array containing 18 elements. Let’s call it an array later. If I want to return the index position corresponding to all elements in the array with a value of 3, this can be easily accomplished through the where function.
print np.where(arr==3)
It will return a tuple containing all index positions corresponding to a value of 3, as shown below:
You can see that the corresponding element value at indexes 5, 9, and 14 is 3. This way you can easily achieve your goal. But this won't work for indexes within a certain range of changes. The following method is a compromise that I came up with. It is relatively stupid, but the master can clear it up.
(2) Solve the search for value index within a certain range through an auxiliary array
We build an array that identifies the element index, Then use it to display the index corresponding to the element that meets the conditions. It's still the same array, if I now want to return the index of the element value between 3 and 100. I can generate an array with the same size as arr, and then first filter it once to find the array corresponding to the index of the element greater than 3, and then filter it again, and finally get the desired result. The code is as follows:
b=np.arange(len(arr))#生成和arr相同长度的数组
c=b[arr>3]#c存放的就是arr中大于3的元素对应的索引 #最后通过遍历c数组,选择3到100之间的值打印出来 for i in range(len(c)): if arr[c[i]]<100: print c[i],
Let’s take a look at the execution effect:
You can see that the program prints out the index values corresponding to all elements between 3 and 100. If you want to get the index value and the corresponding element at the same time, just enter The above "print c[i]" can be replaced with "print c[i],arr[c[i]]".
Of course, this method is also suitable for selecting the index corresponding to a specific value. For example, if I want to find all positions corresponding to 3, I can use print b[arr==3] to print out all values that are 3. The index corresponding to the element. In fact, no matter how you do it, you use an array to perform relational operations to generate a Boolean array, and then display the areas that are True in the array.
Of course, you can also filter twice to filter out the index arrays corresponding to elements greater than 3 and elements less than 100, and then perform intersection processing on the two arrays. There is an intersect1d function in numpy that can do this operation, but it is still troublesome. I can only think of these methods at present. I don’t know if any expert has a better method. Everyone is welcome to share it.
Related recommendations:
Related recommendations:
How to view numpy array attributes in python3 library
How to convert numpy and array in python
The above is the detailed content of Implement ndarray array in numpy to return index method that meets specific conditions. For more information, please follow other related articles on the PHP Chinese website!

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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),

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.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
