- Machine Learning for OpenCV
- Michael Beyeler
- 251字
- 2021-07-02 19:47:18
Accessing single array elements by indexing
If you are familiar with Python's standard list indexing, indexing in NumPy will feel quite familiar. In a 1D array, the i-th value (counting from zero) can be accessed by specifying the desired index in square brackets, just as with Python lists:
In [13]: int_arr
Out[13]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [14]: int_arr[0]
Out[14]: 0
In [15]: int_arr[3]
Out[15]: int_arr[3]
To index from the end of the array, you can use negative indices:
In [16]: int_arr[-1]
Out[16]: 9
In [17]: int_arr[-2]
Out[17]: 8
There are a few other cool tricks for slicing arrays, as follows:
In [18]: int_arr[2:5]: # from index 2 up to index 5 - 1
Out[18]: array([2, 3, 4])
In [19]: int_arr[:5] # from the beginning up to index 5 - 1
Out[19]: array([0, 1, 2, 3, 4])
In [20]: int_arr[5:] # from index 5 up to the end of the array
Out[20]: array([5, 6, 7, 8, 9])
In [21]: int_arr[::2] # every other element
Out[21]: array([0, 2, 4, 6, 8])
In [22]: int_arr[::-1] # the entire array in reverse order
Out[22]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
I encourage you to play around with these arrays yourself!
The general form of slicing arrays in NumPy is the same as it is for standard Python lists. In order to access a slice of an array x, use x[start:stop:step]. If any of these are unspecified, they default to the values start=0, stop=size of dimension, step=1.
推薦閱讀
- ClickHouse性能之巔:從架構設計解讀性能之謎
- ExtGWT Rich Internet Application Cookbook
- Kali Linux Web Penetration Testing Cookbook
- AIRAndroid應用開發(fā)實戰(zhàn)
- Hands-On GPU:Accelerated Computer Vision with OpenCV and CUDA
- Hands-On Full Stack Development with Go
- Kotlin從基礎到實戰(zhàn)
- Visual C++開發(fā)入行真功夫
- Instant Lucene.NET
- Spring Boot+Vue全棧開發(fā)實戰(zhàn)
- Natural Language Processing with Python Quick Start Guide
- Emotional Intelligence for IT Professionals
- 數(shù)據(jù)科學中的實用統(tǒng)計學(第2版)
- 軟件設計模式(Java版)
- Beginning C# 7 Hands-On:The Core Language