
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Access Bottom N Elements from Series Data Structure in Python
Let us understand how the slicing operator ‘:’ can be used to access elements within a certain range.
Example
import pandas as pd my_data = [34, 56, 78, 90, 123, 45] my_index = ['ab', 'mn' ,'gh','kl', 'wq', 'az'] my_series = pd.Series(my_data, index = my_index) print("The series contains following elements") print(my_series) n = 3 print("Bottom 3 elements are :") print(my_series[n:])
Output
The series contains following elements ab 34 mn 56 gh 78 kl 90 wq 123 az 45 dtype: int64 Bottom 3 elements are : kl 90 wq 123 az 45 dtype: int64
Explanation
The required libraries are imported, and given alias names for ease of use.
A list of data values is created, that is later passed as a parameter to the ‘Series’ function present in the ‘pandas’ library
Next, customized index values (that are passed as parameter later) are stored in a list.
A specific range of values can be accessed from the series using indexing ‘:’ operator in Python.
The ‘:’ operator can be used between the lower range value and higher range value: [lower range : higher range].
This will include the lower range value but exclude the higher range value.
If no value is provided for lower range, it is taken as 0.
If no value is provided for higher range, it is taken as len(data structure)-1.
Here, it indicates that the lower range is 3 and higher range is len(data structure)-1.
It is then printed on the console.