![]() |
VOOZH | about |
Pandas Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floats, etc.), with each element having an associated label known as its index. The Series.index attribute in Pandas allows users to get or set the index labels of a Series object, enhancing data accessibility and retrieval efficiency. Example:
Original Index: Index(['a', 'b', 'c', 'd'], dtype='object') Modified Series: w 10 x 20 y 30 z 40 dtype: int64
Explanation: This code creates a Pandas Series with custom index labels ('a', 'b', 'c', 'd') and retrieves the index using data.index. It then updates the index to ('w', 'x', 'y', 'z').
Series.index # Access index labels
Series.index = new_index # Modify index labels
Parameter: This method does not take any parameter.
Returns: Index labels of the Series.
Functionality:
Example 1. Assigning Duplicate Index Labels
Pandas allows assigning duplicate index labels, which can be useful in cases where multiple elements share the same category.
City 1 New York City 1 Chicago City 3 Toronto City 3 Lisbon dtype: object
Explanation: Even with duplicate labels ('City 1' and 'City 3' appearing twice), Pandas maintains the Series structure and ensures data integrity.
Example 2. Retrieving Index Labels
The Series.index attribute can also be used to retrieve the current index labels of a Series.
Index(['Day 1', 'Day 2', 'Day 3', 'Day 4'], dtype='object')
Explanation: The index labels ('Day 1' to 'Day 4') are assigned to a Series and retrieved using series.index.
Example 3. Resetting Index to Default
If needed, we can reset the index to default integer values.
0 1/1/2018 1 2/1/2018 2 3/1/2018 3 4/1/2018 dtype: object
Explanation: reset_index(drop=True, inplace=True) removes the custom index and replaces it with the default integer index while modifying the Series in place.