📜  Python| Pandas Index.unique()(1)

📅  最后修改于: 2023-12-03 14:46:22.715000             🧑  作者: Mango

Python | Pandas Index.unique()

Index.unique() is a method in Pandas library that returns an array of unique values from an index. The returned values are in order of their first occurrence in the index. This method is also available for Series and DataFrame objects as well.

Syntax
Index.unique(self)
Parameters

This method does not take any parameter.

Returns

The method returns an array of unique values from the index.

Example
import pandas as pd

# Creating a simple data frame
data = {'A': [5, 6, 7, 8], 'B': [10, 11, 12, 13]}
df = pd.DataFrame(data)

# Creating a index object
index = pd.Index(['X', 'Y', 'Z', 'W'])

# Adding the index to the data frame
df.set_index(index, inplace=True)

# Getting the unique values from the index
unique_values = df.index.unique()

# Printing the result
print(unique_values)

Output:

Index(['X', 'Y', 'Z', 'W'], dtype='object')

In the above example, we have created a data frame with two columns A and B. Then we created an index object and added it to the data frame. Finally, we have used the unique() method to get the unique values from the index and printed the result.

Note that the returned values are in order of their first occurrence in the index.

This method is useful when we want to know the distinct (unique) values of an index.