Python | Панды Index.factorize ()

Опубликовано: 28 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Pandas Index.factorize() function encode the object as an enumerated type or categorical variable. This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. factorize is available as both a top-level function pandas.factorize(), and as a method Series.factorize() and Index.factorize().

Syntax: Index.factorize(sort=False, na_sentinel=-1)

Parameters :
sort : Sort uniques and shuffle labels to maintain the relationship.
na_sentinel : Value to mark “not found”.

Returns : An integer ndarray that’s an indexer into uniques. uniques.take(labels) will have the same values as values.

Example #1: Use Index.factorize() function to encode the given Index values into categorical form.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index(["Labrador", "Beagle", "Labrador",
                     "Lhasa", "Husky", "Beagle"])
  
# Print the Index
idx

Выход :

Let’s factorize the given Index.

# convert it into categorical values.
idx.factorize()

Output :

As we can see in the output, the Index.factorize() function has converted each label in the Index to a category and has assigned them numerical values.
 
Example #2: Use Index.factorize() function to factorize the index values based on their sorted order sequence.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index(["Jan", "Feb", "Mar", "Apr", "May", "Jun",
               "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
  
# Print the Index
idx

Выход :

Let’s factorize it based on sorted order. Numerical values are assigned only after the sorting of the values in the Index.

# Factorize the sorted labels
idx.factorize(sort = True)

Выход :

Как видно из выходных данных, перед присвоением им числовых значений была проведена сортировка значений индекса.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.