Pandas How To Uncategorized How to use unique in Pandas

How to use unique in Pandas

In Pandas, the unique() method can be used to extract unique values from a Pandas Series or DataFrame. Here are some examples:

Series

import pandas as pd

# create a Series
s = pd.Series([1, 2, 3, 1, 2, 3, 4, 5])

# extract unique values
unique_values = s.unique()

# print unique values
print(unique_values)

Output:

[1 2 3 4 5]

DataFrame

import pandas as pd

# create a DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'a', 'b', 'c', 'd', 'e']
})

# extract unique values from column A
unique_values_colA = df['A'].unique()

# extract unique values from column B
unique_values_colB = df['B'].unique()

# print unique values
print(unique_values_colA)
print(unique_values_colB)

Output:

[1 2 3 4 5]
['a' 'b' 'c' 'd' 'e']

The unique() method returns an array of unique values in the same order as they appear in the original Series or DataFrame. It can be useful to check for unique values in a column or to filter out duplicates in a dataset.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post