JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Get unique values in a Pandas column and sort them

Author:JIYIK Last Updated:2025/05/02 Views:

This article will show you how to get the unique values ​​in a Pandas DataFrame column.

For example, suppose we have a DataFrame consisting of individuals and their occupations, and we want to know the total number of occupations. In this case, we cannot simply use the total number of rows to determine the total number of unique occupations, as many people may have the same job. For this case, we can use the unique()sum drop_duplicates()function provided by the Pandas library.

It is also important to know how to sort a DataFrame as it can help visualize and understand the data. The sorted()and sort_values()functions can help with this.

We will sort and delete the following DataFrame in this tutorial.

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": [7, 1, 5, 4, 2, 1, 4, 4, 8], "B": [1, 2, 8, 5, 3, 4, 2, 6, 8]})

print(df)

Output:

   A  B
0  7  1
1  1  2
2  5  8
3  4  5
4  2  3
5  1  4
6  4  2
7  4  6
8  8  8

uniqueGet unique values ​​in a Pandas DataFrame column using

Pandas Series’s unique()get method is used when we process a single column of a DataFrame and returns all the unique elements of a column. unique()The final output of using the get function is an array.

example:

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": [7, 1, 5, 4, 2, 1, 4, 4, 8], "B": [1, 2, 8, 5, 3, 4, 2, 6, 8]})

print(df["A"].unique())
print(type(df["A"].unique()))

Output:

[7 1 5 4 2 8]
numpy.ndarray

drop_duplicatesGet unique values ​​in a Pandas DataFrame column using

drop_duplicates()Can be applied to a DataFrame or a subset thereof and preserves the type of the DataFrame object. It is also considered a faster option when processing huge datasets to remove duplicate values.

example:

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": [7, 1, 5, 4, 2, 1, 4, 4, 8], "B": [1, 2, 8, 5, 3, 4, 2, 6, 8]})

print(df.drop_duplicates(subset="A"))
print(type(df.drop_duplicates(subset="A")))

Output:

   A  B
0  7  1
1  1  2
2  5  8
3  4  5
4  2  3
8  8  8
pandas.core.frame.DataFrame

Sorting columns in a Pandas DataFrame

We can sorted()sort a column using the method, but it converts the final result into a list type object. We can also sort the column values ​​in descending order by reversedsetting the parameter to .True

The following example sorts a column in ascending order and removes duplicate values.

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": [7, 1, 5, 4, 2, 1, 4, 4, 8], "B": [1, 2, 8, 5, 3, 4, 2, 6, 8]})

df_new = df.drop_duplicates(subset="A")

print(sorted(df_new["A"]))
print(type(sorted(df_new["A"])))

Output:

[1, 2, 4, 5, 7, 8]
list

sort_values()is another flexible option to sort a DataFrame. Here, we can byspecify the column to be sorted using the argument and ascendingwhether the order should be ascending or descending using the argument. It retains the object type as Pandas DataFrame.

The following example sorts the column in descending order and removes duplicate values.

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": [7, 1, 5, 4, 2, 1, 4, 4, 8], "B": [1, 2, 8, 5, 3, 4, 2, 6, 8]})

df_new = df.drop_duplicates(subset="A")

print(df_new.sort_values(by="A", ascending=False))
type(df_new.sort_values(by="A"))

Output:

   A  B
8  8  8
0  7  1
2  5  8
3  4  5
4  2  3
1  1  2
pandas.core.frame.DataFrame

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to Convert DataFrame Column to String in Pandas

Publish Date:2025/05/02 Views:161 Category:Python

We will look at methods for converting Pandas DataFrame columns to strings. Pandas Series.astype(str) Method DataFrame.apply() Methods operate on the elements in a column We will use the same DataFrame below in this article. import pandas a

How to count the frequency of values in a Pandas DataFrame

Publish Date:2025/05/02 Views:84 Category:Python

Sometimes, when you use DataFrame , you may want to count the number of times a value occurs in a column, or in other words, calculate the frequency. There are mainly three methods used for this. Let's look at them one by one. df.groupby().

How to get value from Pandas DataFrame cell

Publish Date:2025/05/02 Views:147 Category:Python

We'll look at using to get values ​​from cells in iloc Pandas , which is great for selecting by position, and how it differs from . We'll also learn about the and methods, which we can use when we don't want to set the return type to .

How to Add a Row to a Pandas DataFrame

Publish Date:2025/05/02 Views:127 Category:Python

Pandas is designed to load a fully populated DataFrame . We can pandas.DataFrame add them one by one in . This can be done by using various methods, such as .loc , dictionary, pandas.concat() or DataFrame.append() . .loc [index] Add rows to

How to change the order of Panas DataFrame columns

Publish Date:2025/05/02 Views:184 Category:Python

We will show how to use insert and reindex to change the order of columns in different ways pandas.DataFrame , such as assigning column names in a desired order. pandas.DataFrame Sort the columns in the new order The easiest way is columns

How to pretty print an entire Pandas Series/DataFrame

Publish Date:2025/05/02 Views:167 Category:Python

We will introduce various methods to pretty print the entire Pandas Series/DataFrame, such as option_context, set_option, and options.display. option_context Pretty Printing Pandas DataFrame We can option_context use with one or more option

How to Convert a Pandas Dataframe to a NumPy Array

Publish Date:2025/05/02 Views:151 Category:Python

We will introduce to_numpy() the method to pandas.Dataframe convert a to NumPy an array, which is introduced in pandas v0.24.0, replacing the old .values method. We can define it on Index , Series , and DataFrame objects to_numpy . The old

How to add a header row to a Pandas DataFrame

Publish Date:2025/05/02 Views:161 Category:Python

We will look at methods for adding a header row to a pandas dataframe, as well as the option to pass in the names directly in the dataframe or by assigning the column names in a list directly to dataframe.columns the method. We will also in

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial