- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Accessing elements of a Pandas Series
Pandas series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The elements of a pandas series can be accessed using various methods.
Let's first create a pandas series and then access it's elements.
Creating Pandas Series
A panadas series is created by supplying data in various forms like ndarray, list, constants and the index values which must be unique and hashable. An example is given below.
Example
import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s
Output
Running the above code gives us the following result −
a 11 b 8 c 6 d 14 e 25 dtype: int64
Accessing elements of a series
We can access the data elements of a series by using various methods. We will continue to use the series created above to demonstrate the various methods of accessing.
Accessing the First Element
The first element is at the index 0 position. So it is accessed by mentioning the index value in the series. We can use both 0 or the custom index to fetch the value.
Example
import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s[0] print s['a']
Output
Running the above code gives us the following result −
11 11
Accessing the First Three Elements
In a similar manner as above we get the first three elements by using the : value in front of the index value of 3 or the appropriate custom index value.
Example
import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s[:3] print s[:'c']
Output
Running the above code gives us the following result −
a 11 b 8 c 6 dtype: int64 a 11 b 8 c 6 dtype: int64
Accessing the Last Three Elements
In a similar manner as above, we get the first three elements by using the: value at the end of the index value of 3 with a negative sign or the appropriate custom index value.
Example
import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s[-3:] print s['c':]
Output
Running the above code gives us the following result −
c 6 d 14 e 25 dtype: int64 c 6 d 14 e 25 dtype: int64
Accessing Elements using Index Labels
In this case, we use the custom index values to access non-sequential elements of the series.
Example
import pandas as pd s = pd.Series([11,8,6,14,25],index = ['a','b','c','d','e']) print s[['c','b','e']]
Output
Running the above code gives us the following result −
c 6 b 8 e 25 dtype: int64