Pandas – Get All Unique Values in a Column
In this tutorial, we will look at how to get a list of unique values in a pandas dataframe column. Additionally, we will also look at how to get a count of each unique value within the column and the total unique count.
First, let’s create a sample dataframe that we will be using throughout this tutorial for demonstrating the usage.
Now we have a dataframe with 10 rows and three columns storing information on height, weight, and teams of top scorers in a football competition.
1. List of all unique values in a pandas dataframe column
You can use the pandas unique() function to get the different unique values present in a column. It returns a numpy array of the unique values in the column. For example, let’s see what are the unique values present in the column “Team” of the dataframe “df” created above.
You can see we get a numpy array of all the unique values present in the column “Team” – “A”, “B”, and “C”.
For more on the pandas unique() function, refer to its documentation.
2. Count of unique values in a column
If you just need the count of unique values present in a pandas dataframe column, you can use the pandas nunique() function. It returns the number of unique values present in the dataframe as an integer. For example, let’s count the number of unique values in the column “Team” of the dataframe “df”.
We get 3 as the output because there are three unique values present in the column “Team”. Note that you can use the nunique() function to count the unique values in a row as well.
3. Count of each unique value in a column
You can use the pandas value_counts() function to get the number of times each unique value occurs in a column. For example, let’s find the what’s the count of each unique value in the “Team” column.
You can see that the value “B” occurs 4 times, and “A” and “C” occur 3 times each in the column “Team”. The value_counts() is a nice function to check the distribution of data points across a categorical field.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Find the unique values in a column and then sort them
I have a pandas dataframe. I want to print the unique values of one of its columns in ascending order. This is how I am doing it:
The problem is that I am getting a None for the output.
8 Answers 8
sorted(iterable) : Return a new sorted list from the items in iterable.
CODE
OUTPUT
![]()
![]()
sort sorts inplace so returns nothing:
So you have to call print a again after the call to sort .
You can also use the drop_duplicates() instead of unique()
Came across the question myself today. I think the reason that your code returns ‘None’ (exactly what I got by using the same method) is that
is calling the sort function to mutate the list a. In my understanding, this is a modification command. To see the result you have to use print(a).
Моя шпаргалка по pandas
Один преподаватель как-то сказал мне, что если поискать аналог программиста в мире книг, то окажется, что программисты похожи не на учебники, а на оглавления учебников: они не помнят всего, но знают, как быстро найти то, что им нужно.
Возможность быстро находить описания функций позволяет программистам продуктивно работать, не теряя состояния потока. Поэтому я и создал представленную здесь шпаргалку по pandas и включил в неё то, чем пользуюсь каждый день, создавая веб-приложения и модели машинного обучения.

Нельзя сказать, что это — исчерпывающий список возможностей pandas , но сюда входят функции, которыми я пользуюсь чаще всего, примеры и мои пояснения по поводу ситуаций, в которых эти функции особенно полезны.
1. Подготовка к работе
Если вы хотите самостоятельно опробовать то, о чём тут пойдёт речь, загрузите набор данных Anime Recommendations Database с Kaggle. Распакуйте его и поместите в ту же папку, где находится ваш Jupyter Notebook (далее — блокнот).
Теперь выполните следующие команды.
После этого у вас должна появиться возможность воспроизвести то, что я покажу в следующих разделах этого материала.
2. Импорт данных
▍Загрузка CSV-данных
Здесь я хочу рассказать о преобразовании CSV-данных непосредственно в датафреймы (в объекты Dataframe). Иногда при загрузке данных формата CSV нужно указывать их кодировку (например, это может выглядеть как encoding=’ISO-8859–1′ ). Это — первое, что стоит попробовать сделать в том случае, если оказывается, что после загрузки данных датафрейм содержит нечитаемые символы.

Загруженные CSV-данные
Существует похожая функция для загрузки данных из Excel-файлов — pd.read_excel .
▍Создание датафрейма из данных, введённых вручную
Это может пригодиться тогда, когда нужно вручную ввести в программу простые данные. Например — если нужно оценить изменения, претерпеваемые данными, проходящими через конвейер обработки данных.

Данные, введённые вручную
▍Копирование датафрейма
Копирование датафреймов может пригодиться в ситуациях, когда требуется внести в данные изменения, но при этом надо и сохранить оригинал. Если датафреймы нужно копировать, то рекомендуется делать это сразу после их загрузки.

Копия датафрейма
3. Экспорт данных
▍Экспорт в формат CSV
При экспорте данных они сохраняются в той же папке, где находится блокнот. Ниже показан пример сохранения первых 10 строк датафрейма, но то, что именно сохранять, зависит от конкретной задачи.
Экспортировать данные в виде Excel-файлов можно с помощью функции df.to_excel .
4. Просмотр и исследование данных
▍Получение n записей из начала или конца датафрейма
Сначала поговорим о выводе первых n элементов датафрейма. Я часто вывожу некоторое количество элементов из начала датафрейма где-нибудь в блокноте. Это позволяет мне удобно обращаться к этим данным в том случае, если я забуду о том, что именно находится в датафрейме. Похожую роль играет и вывод нескольких последних элементов.

Данные из начала датафрейма

Данные из конца датафрейма
▍Подсчёт количества строк в датафрейме
Функция len(), которую я тут покажу, не входит в состав pandas . Но она хорошо подходит для подсчёта количества строк датафреймов. Результаты её работы можно сохранить в переменной и воспользоваться ими там, где они нужны.
▍Подсчёт количества уникальных значений в столбце
Для подсчёта количества уникальных значений в столбце можно воспользоваться такой конструкцией:
▍Получение сведений о датафрейме
В сведения о датафрейме входит общая информация о нём вроде заголовка, количества значений, типов данных столбцов.

Сведения о датафрейме
Есть ещё одна функция, похожая на df.info — df.dtypes . Она лишь выводит сведения о типах данных столбцов.
▍Вывод статистических сведений о датафрейме
Знание статистических сведений о датафрейме весьма полезно в ситуациях, когда он содержит множество числовых значений. Например, знание среднего, минимального и максимального значений столбца rating даёт нам некоторое понимание того, как, в целом, выглядит датафрейм. Вот соответствующая команда:

Статистические сведения о датафрейме
▍Подсчёт количества значений
Для того чтобы подсчитать количество значений в конкретном столбце, можно воспользоваться следующей конструкцией:

Подсчёт количества элементов в столбце
5. Извлечение информации из датафреймов
▍Создание списка или объекта Series на основе значений столбца
Это может пригодиться в тех случаях, когда требуется извлекать значения столбцов в переменные x и y для обучения модели. Здесь применимы следующие команды:

Результаты работы команды anime[‘genre’].tolist()

Результаты работы команды anime[‘genre’]
▍Получение списка значений из индекса
Поговорим о получении списков значений из индекса. Обратите внимание на то, что я здесь использовал датафрейм anime_modified , так как его индексные значения выглядят интереснее.

Результаты выполнения команды
▍Получение списка значений столбцов
Вот команда, которая позволяет получить список значений столбцов:

Результаты выполнения команды
6. Добавление данных в датафрейм и удаление их из него
▍Присоединение к датафрейму нового столбца с заданным значением
Иногда мне приходится добавлять в датафреймы новые столбцы. Например — в случаях, когда у меня есть тестовый и обучающий наборы в двух разных датафреймах, и мне, прежде чем их скомбинировать, нужно пометить их так, чтобы потом их можно было бы различить. Для этого используется такая конструкция:
▍Создание нового датафрейма из подмножества столбцов
Это может пригодиться в том случае, если требуется сохранить в новом датафрейме несколько столбцов огромного датафрейма, но при этом не хочется выписывать имена столбцов, которые нужно удалить.

Результат выполнения команды
▍Удаление заданных столбцов
Этот приём может оказаться полезным в том случае, если из датафрейма нужно удалить лишь несколько столбцов. Если удалять нужно много столбцов, то эта задача может оказаться довольно-таки утомительной, поэтому тут я предпочитаю пользоваться возможностью, описанной в предыдущем разделе.

Результаты выполнения команды
▍Добавление в датафрейм строки с суммой значений из других строк
Для демонстрации этого примера самостоятельно создадим небольшой датафрейм, с которым удобно работать. Самое интересное здесь — это конструкция df.sum(axis=0) , которая позволяет получать суммы значений из различных строк.

Результат выполнения команды
Команда вида df.sum(axis=1) позволяет суммировать значения в столбцах.
Похожий механизм применим и для расчёта средних значений. Например — df.mean(axis=0) .
7. Комбинирование датафреймов
▍Конкатенация двух датафреймов
Эта методика применима в ситуациях, когда имеются два датафрейма с одинаковыми столбцами, которые нужно скомбинировать.
В данном примере мы сначала разделяем датафрейм на две части, а потом снова объединяем эти части:

Датафрейм df1

Датафрейм df2

Датафрейм, объединяющий df1 и df2
▍Слияние датафреймов
Функция df.merge , которую мы тут рассмотрим, похожа на левое соединение SQL. Она применяется тогда, когда два датафрейма нужно объединить по некоему столбцу.

Результаты выполнения команды
8. Фильтрация
▍Получение строк с нужными индексными значениями
Индексными значениями датафрейма anime_modified являются названия аниме. Обратите внимание на то, как мы используем эти названия для выбора конкретных столбцов.

Результаты выполнения команды
▍Получение строк по числовым индексам
Эта методика отличается от той, которая описана в предыдущем разделе. При использовании функции df.iloc первой строке назначается индекс 0 , второй — индекс 1 , и так далее. Такие индексы назначаются строкам даже в том случае, если датафрейм был модифицирован и в его индексном столбце используются строковые значения.
Следующая конструкция позволяет выбрать три первых строки датафрейма:

Результаты выполнения команды
▍Получение строк по заданным значениям столбцов
Для получения строк датафрейма в ситуации, когда имеется список значений столбцов, можно воспользоваться следующей командой:

Результаты выполнения команды
Если нас интересует единственное значение — можно воспользоваться такой конструкцией:
▍Получение среза датафрейма
Эта техника напоминает получение среза списка. А именно, речь идёт о получении фрагмента датафрейма, содержащего строки, соответствующие заданной конфигурации индексов.

Результаты выполнения команды
▍Фильтрация по значению
Из датафреймов можно выбирать строки, соответствующие заданному условию. Обратите внимание на то, что при использовании этого метода сохраняются существующие индексные значения.

Результаты выполнения команды
9. Сортировка
Для сортировки датафреймов по значениям столбцов можно воспользоваться функцией df.sort_values :

Результаты выполнения команды
10. Агрегирование
▍Функция df.groupby и подсчёт количества записей
Вот как подсчитать количество записей с различными значениями в столбцах:

Результаты выполнения команды
▍Функция df.groupby и агрегирование столбцов различными способами
Обратите внимание на то, что здесь используется reset_index() . В противном случае столбец type становится индексным столбцом. В большинстве случаев я рекомендую делать то же самое.
▍Создание сводной таблицы
Для того чтобы извлечь из датафрейма некие данные, нет ничего лучше, чем сводная таблица. Обратите внимание на то, что здесь я серьёзно отфильтровал датафрейм, что ускорило создание сводной таблицы.

Результаты выполнения команды
11. Очистка данных
▍Запись в ячейки, содержащие значение NaN, какого-то другого значения
Здесь мы поговорим о записи значения 0 в ячейки, содержащие значение NaN . В этом примере мы создаём такую же сводную таблицу, как и ранее, но без использования fill_value=0 . А затем используем функцию fillna(0) для замены значений NaN на 0 .

Таблица, содержащая значения NaN

Результаты замены значений NaN на 0
12. Другие полезные возможности
▍Отбор случайных образцов из набора данных
Я использую функцию df.sample каждый раз, когда мне нужно получить небольшой случайный набор строк из большого датафрейма. Если используется параметр frac=1 , то функция позволяет получить аналог исходного датафрейма, строки которого будут перемешаны.

Результаты выполнения команды
▍Перебор строк датафрейма
Следующая конструкция позволяет перебирать строки датафрейма:

Результаты выполнения команды
▍Борьба с ошибкой IOPub data rate exceeded
Если вы сталкиваетесь с ошибкой IOPub data rate exceeded — попробуйте, при запуске Jupyter Notebook, воспользоваться следующей командой:
Итоги
Здесь я рассказал о некоторых полезных приёмах использования pandas в среде Jupyter Notebook. Надеюсь, моя шпаргалка вам пригодится.
Уважаемые читатели! Есть ли какие-нибудь возможности pandas , без которых вы не представляете своей повседневной работы?
How to Use Pandas Unique to Get Unique Values
In this tutorial I’ll show you how to use the Pandas unique technique to get unique values from Pandas data.
I’ll explain the syntax, including how to use the two different forms of Pandas unique: the unique function as well as the unique method. (There are actually two different ways to use this technique in Pandas. I’ll show you both.)
If you’re here for something specific, you can click on any of the links below, and it will take you to the appropriate section of the tutorial.
Table of Contents:
But, if you read everything from start to finish, it will probably make more sense.
Having said that, let’s get started.
A Quick Introduction to Pandas Unique
The Pandas Unique technique identifies the unique values in Pandas series objects and other types of objects.
If you’re somewhat new to Pandas, that might not make sense, so let me quickly explain.
Pandas is a Data Manipulation Toolkit
Just a quick review for people who are new to Pandas: Pandas is a data manipulation toolkit for Python.
We use Pandas to retrieve, clean, subset, and reshape data in Python.
Pandas Tools Work on DataFrames and Series Objects
There are two main data structures in Pandas.
First, there is the Pandas dataframe, which is a row-and-column data structure. A dataframe is sort of like an Excel spreadsheet, in the sense that it has rows and columns. Dataframes look something like this:

The second major Pandas data structure is the Pandas Series.
A Pandas Series is like a single column of data.

The Syntax of Pandas Unique
Ok. Let’s take a look at the syntax.
The syntax is fairly simple and straightforward, but there are a few important details.
Notably, there are actually two different ways to use the unique() technique. You can use unique() as a Pandas function, but you can also use it as a method.
We’ll take a look at the syntax of each independently.
A quick note
One quick note: going forward, I’m going to assume that you’ve imported the Pandas library with the alias ‘pd’.
You can do that with the following code:
The syntax of pd.unique
Ok. Let’s start by taking a look at the pd.unique function.
When we use the unique function, we can call it like this:

We call the function as pd.unique() .
Inside the parenthesis, we provide the name of the Series that we want to operate on. Keep in mind, that this can be an actual Series, but the function will also work if you provide an “array like” object, such as a Python list.
The syntax of the Pandas Unique Method
In the previous section, we looked at how to call the unique() function.
Here, I’ll explain how to use unique as a method. (Remember, a method is like a function that’s associated with an object.)
When you use the method version, you start by typing the name of the Series object that you want to work with.
Next, you type a “dot,” and then the name of the method, unique() .

When we use the Pandas unique method, we can use it on a lone Series object that exists on it’s own, outside of a dataframe.
Having said that, it’s probably more common to use unique() on dataframe columns.
Let’s take a look at how to do that.
How to use unique on a dataframe column
As I’ve already mentioned dataframe columns are essentially Pandas Series objects. If you want to use the unique() method on a dataframe column, you can do so as follows:
Type the name of the dataframe, then use “dot syntax” and type the name of the column. Then use dot syntax to call the unique() method.
The Output of Unique()
Whether we use the function form or the method form, the output is the same.
The unique() technique produces a Numpy array with the unique values.
Moreover, keep in mind that the unique values are returned in the order that they appear in the input series. So they are not sorted in the output.
[Note that “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.” See official documentation for Pandas unique.]
Examples: How to Identify Unique Values in Pandas
Ok. Now that you’ve learned about the syntax, let’s look at some concrete examples.
You can click on any of the following links, and it will take you directly to the example.
Examples:
Run this code first
Two quick pieces of setup, before you run the examples.
You need to import Pandas, and retrieve a dataset.
Import Pandas and Seaborn
First you need to import Pandas and Seaborn with the following code.
We will use Seaborn to retrieve a dataset.
Retrieve Titanic Dataframe
Next, we’ll retrieve the titanic dataframe.
We can do this with the sns.load_dataset() function as follows:
We won’t use this dataframe for all of the examples, but we will use it for one of them.
EXAMPLE 1: Identify the Unique Values of a List
First, we’ll start simple.
Here, instead of working with more complex data structures, we’ll just work with a simple Python list.
First, let’s just create a simple Python list with 7 values.
The list, letter_list , contains several capital letters. Notice that there are several repeated letters.
Explanation
Here, the input was a simple Python list that contains several letters. Some of the letters were repeated.
The output is a Numpy array that contains the unique values that were in the input. In other words, the output array contains the same values, but with all of the duplicates removed.
Furthermore, notice the order. The items in the output are not sorted. Instead, the items in the output appear in the same order that they originally appeared in the input.
EXAMPLE 2: Get unique values from Pandas Series using unique function
Next, let’s get the unique values from a Pandas Series.
Here, we’ll again use the unique() function to do this.
First though, let’s quickly create a Series object:
And now, let’s identify the unique values:
Explanation
Again, this is fairly simple.
Here, we’re calling the pd.unique() function to get the unique values.
The input to the function is the animals Series (a Pandas Series object).
The output is a Numpy array.
Notice again that the items in the output are de-duped … the duplicates are removed.
Moreover, they appear in the exact same order as they appeared in the input. They are unsorted.
EXAMPLE 3:Get unique values from Pandas Series using unique method
Next, let’s use the unique() method to get unique values.
So in the previous example, we used the unique function to compute the unique values. But here, we’re going to use the method (if you’re confused about this, review our explanation of the function version and the method version in the section about syntax.)
First, we can create our Series object (this is the same Series as the previous example).
Next, let’s use the method syntax to retrieve the unique values.
Explanation
Here, we’ve used the method syntax to retrieve the unique values that are contained in a Pandas series.
To do this, we typed the name of the Series object, animals .
Then, we used so-called “dot syntax” to call the unique() method. When we use the unique() technique this way, it simply identifies the unique values that are contained in the associated Series object. As an output, it produces a Numpy array with the unique values.
EXAMPLE 4: Identify the Unique Values of a DataFrame Column
Finally, let’s do one more example.
Here, we’ll identify the unique values of a dataframe column.
Specifically, we’ll identify the unique values of the embark_town variable in the titanic dataset.
First, let’s get the titanic dataframe using sns.load_dataset() .
Next, we can retrieve the unique values of the embark_town column by using the method syntax as follows:
Explanation
Here, we’re using the method syntax to identify the unique values of a dataframe column.
I explained this in the syntax section, but let me quickly repeat, for clarity.
When we get the unique values of a column, we need to type the name of the dataframe, then the name of the column, and then unique() . Keep in mind that these must be separated by ‘dots.’

Leave your questions in the comments below
Do you still have questions about the Pandas Unique technique?
Just leave your questions in the comments section near the bottom of the page.
If you want to master Pandas, join our course
In this tutorial, I’ve explained how to use the unique function, but if you want to master data manipulation in Pandas, there’s really a lot more to learn.
So if you really want to master data wrangling with Pandas, you should join our premium online course, Pandas Mastery.
Pandas Mastery is our online course that will teach you these critical data manipulation tools.
Inside the course, you’ll learn all of the essentials of data manipulation in pandas, like:
- subsetting data
- filtering data by logical conditions
- adding new variables
- reshaping data
- working with Pandas indexes
- and much more …
Additionally, you’ll discover our unique practice system that will enable you to memorize all of the syntax you learn. Memorizing the syntax will only take a few weeks!