Pandas: Series - unique() function
Unique values of Series object in Pandas
The unique() function is used to get unique values of Series object.
Uniques are returned in order of appearance. Hash table-based unique, therefore does NOT sort.
Syntax:
Series.unique(self)
Returns: ndarray or ExtensionArray
The unique values returned as a NumPy array. See Notes.
Notes: Returns the unique values as a NumPy array. In case of an extension-array backed Series, a new ExtensionArray of that type with just the unique values is returned. This includes
- Categorical
- Period
- Datetime with Timezone
- Interval
- Sparse
- IntegerNA
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
pd.Series([2, 4, 3, 3], name='P').unique()
Output:
array([2, 4, 3], dtype=int64)
Python-Pandas Code:
import numpy as np
import pandas as pd
pd.Series([2, 4, 3, 3], name='P').unique()
pd.Series([pd.Timestamp('2019-01-01') for _ in range(3)]).unique()
Output:
array(['2019-01-01T00:00:00.000000000'], dtype='datetime64[ns]')
Python-Pandas Code:
import numpy as np
import pandas as pd
pd.Series([2, 4, 3, 3], name='P').unique()
pd.Series([pd.Timestamp('2019-01-01', tz='US/Eastern')
for _ in range(3)]).unique()
Output:
['2019-01-01 00:00:00-05:00'] Length: 1, dtype: datetime64[ns, US/Eastern]
Example - An unordered Categorical will return categories in the order of appearance:
Python-Pandas Code:
import numpy as np
import pandas as pd
pd.Series(pd.Categorical(list('qppqr'))).unique()
Output:
[q, p, r] Categories (3, object): [q, p, r]
Example - An ordered Categorical preserves the category ordering:
Python-Pandas Code:
import numpy as np
import pandas as pd
pd.Series(pd.Categorical(list('qppqr'), categories=list('pqr'),
ordered=True)).unique()
Output:
[q, p, r] Categories (3, object): [p < q < r]
Previous: Sum of the values for the requested axis in Pandas
Next: Series containing counts of unique values in Pandas
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/series/series-unique.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics