- How to get the index and values of series in Pandas?
- Example
- Explanation
- Output
- Example
- Explanation
- Output
- How to Get Index of Series in Pandas
- 1. Quick Examples of Getting Series Index
- 2. Syntax of Pandas Series.index
- 3. Create Pandas Series
- 4. Get the Index in Pandas Series
- 5. Get the Custom Index in Series
- Conclusion
- Related Articles
- References
- You may also like reading:
- How to find element’s index in pandas Series?
- Preparing dataset
- Find index of an element in pandas Series using index attribute
- Frequently Asked:
- Find index of an element in pandas Series using get_loc() method
- Find index of an element in pandas Series using numpy.where() function
- Summary
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
How to get the index and values of series in Pandas?
A pandas Series holds labeled data, by using these labels we can access series elements and we can do manipulations on our data. However, in some situations, we need to get all labels and values separately.
Labels can be called indexes and data present in a series called values. If you want to get labels and values individually. Then we can use the index and values attributes of the Series object.
Let’s take an example and see how these attributes will work.
Example
import pandas as pd # creating a series s = pd.Series() print(s) # Getting values and index data index = s.index values = s.values print('
') # displaying outputs print(index) print(values)
Explanation
Created a pandas Series using a python dictionary with integer keys and string values pairs. And index and values are the series attributes that will return a ndarray of indexes and values.
The s.index and s.values will return an ndarray and those arrays are stored in index and values variables respectively. And at the end, we print the results by using the print function.
Output
97 a 98 b 99 c 100 d 101 e 102 f dtype: object Int64Index([97, 98, 99, 100, 101, 102], dtype='int64') array(['a', 'b', 'c', 'd', 'e', 'f'], dtype=object)
This block of output has a pandas Series which is created by using a python dictionary, the created series is having labeled data. and the second block the above output is representing values and index data in a ndarray format.
We can see data type each output in the above block, here values are object dtype and indexes are int64 dtype.
Example
import pandas as pd # creating a series s = pd.Series([-2.3, np.nan, 9, 6.5, -5, -8, np.nan]) print(s) # Getting values and index data index = s.index values = s.values print('
') # displaying outputs print(index) print(values)
Explanation
In the following example we have created a pandas Series using a python list and without index representation.
Output
0 -2.3 1 NaN 2 9.0 3 6.5 4 -5.0 5 -8.0 6 NaN dtype: float64 RangeIndex(start=0, stop=7, step=1) [-2.3 nan 9. 6.5 -5. -8. nan]
The s.index attribute will return an ndarray normally, but in this case we haven’t specified any index values at the time of series creation. Due to this we can see the index values as RangeIndex format.
How to Get Index of Series in Pandas
Pandas Series.index attribute is used to get the index labels of the given Series object. A pandas Series holds labeled data and these labels are called indexes, by using these labels we can access series elements and we can do manipulations on our data.
In some situations, we need to get all labels and values separately, using this attribute we can get only index labels. In this article, I will explain how to get index values/labels in pandas Series with examples.
1. Quick Examples of Getting Series Index
If you are in hurry below are some quick examples of how to get the pandas series index.
# Below are the quick examples # Example 1 : Create pandas series courses = pd.Series(['Java', 'Spark', 'PySpark','Pandas','NumPy', 'Python']) # Example 2 : Get the indices of Series courses.index = ['Course1', 'Course2', 'Course3', 'Course4', 'Course5', 'Course6']
2. Syntax of Pandas Series.index
Following is the syntax of the Series.index .
# Syntax of series.index series.index()
3. Create Pandas Series
Pandas Series is a one-dimensional, Index-labeled data structure that is available only in the Pandas library. It can store all the datatypes such as strings, integer, float, and other python objects. We can access each element in the Series with the help of corresponding default indices.
Note : Series data structure is same as the NumPy array data structure but only one difference that is arrays indices are integers and starts with 0, whereas in series, the index can be anything even strings. The labels do not need to be unique but they must be of hashable type.
# Create the Series import pandas as pd courses = pd.Series(['Java', 'Spark', 'PySpark','Pandas','NumPy', 'Python']) print(courses)
Yields below output. When you create a series without an index, pandas create a default index with an incremental sequence number starting from 0.
# Output: 0 Java 1 Spark 2 PySpark 3 Pandas 4 NumPy 5 Python dtype: object
4. Get the Index in Pandas Series
In Series, labels are called indices, and holding the data is called values. If we use Series.index attribute we can get the labels. Let’s apply this attribute to the above Series, it will return the indices of the series. When you have a default index it returns the RangeIndex .
# Get the default indices of Series. print(courses.index) print(type(courses.index)) # Output: # RangeIndex(start=0, stop=6, step=1) #
From the above, we got the default indices in the form of a range from 0 to 6.
5. Get the Custom Index in Series
We can also create the Series with customized index labels for, that we need to pass the index as a list of values into pd.series() function.
# Create pandas Series courses = pd.Series(['Java', 'Spark', 'PySpark','Pandas','NumPy', 'Python'], index = ['Course1', 'Course2', 'Course3', 'Course4', 'Course5', 'Course6']) print(courses)
# Output: Course1 Java Course2 Spark Course3 PySpark Course4 Pandas Course5 NumPy Course6 Python dtype: object
As we can see in the output, the Series.index attribute has successfully set the index labels for the given Series object.
Now, this time we can get the customized indices of the Series individually for, that we need to print only index values.
# Get the custom index print(courses.index) print(type(courses.index)) # Output: # Index(['Course1', 'Course2', 'Course3', 'Course4', 'Course5', 'Course6'], dtype='object')
Conclusion
In this article, I have explained the pandas.series.index attribute is used to get the Series index. also, covered what you get when you have a default index and custom index.
Related Articles
References
You may also like reading:
How to find element’s index in pandas Series?
In this article, we will discuss multiple ways to find an element’s index in the pandas Series.
Table of Content
Preparing dataset
To quickly get started, let’s create a sample pandas Series for experimentation.
import pandas as pd import numpy as np new_series = pd.Series([1,4,0,7,5,4,9], index=[0,1,2,3,4,5,6]) print(new_series)
Content of the created Series is,
0 1 1 4 2 0 3 7 4 5 5 4 6 9 dtype: int64
Find index of an element in pandas Series using index attribute
The simplest way to find the element’s index is to filter for the specific element and use the index property of the pandas Series. For example, to get the index of element “0” from the above pandas Series, we can do the following
Frequently Asked:
# get the index of element "0" indexPos = new_series[new_series==0].index[0] print(indexPos)
To break down the code, we first filtered the Series to find the element “0” and then used the “.index” to get the index values of the same.
In case of multiple values, the index attribute will return all the matched indexes, from which we can select the nth value. To understand better, let’s find the index of the element “4”.
# get the indices of element "4" indexValues = new_series[new_series==4].index print(indexValues)
As observed, the element “4” is present on the index 1 and 5 both. We can select the desired index by passing it in the list element (“[n]”) as above.
Find index of an element in pandas Series using get_loc() method
Another method is to use “get_loc()” method to get the index of the desired element. Let’s understand with an example, by finding the index of the element “0”.
# get the index of element "0" indexPos = pd.Index(new_series).get_loc(0) print(indexPos)
Here, we have first converted the series into pandas Index object and then used “get_loc” function to get the location of the “0” element.
Find index of an element in pandas Series using numpy.where() function
Another way is to use the numpy.where function to get the element’s index. Let’s understand with the same example as above.
# get the index of element "0" indexPos = np.where(new_series== 0)[0][0] print(indexPos)
We have similar output as the above methods.
Summary
Today we learned about different techniques to find an element’s index in pandas Series in Python. Thanks.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.