
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
Get 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({97:'a', 98:'b', 99:'c', 100:'d', 101:'e', 102:'f'}) 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.