Python categorical to number

Как преобразовать категориальную переменную в числовую в Pandas

Вы можете использовать следующий базовый синтаксис для преобразования категориальной переменной в числовую переменную в кадре данных pandas:

df['column_name'] = pd.factorize(df['column_name'])[0] 

Вы также можете использовать следующий синтаксис для преобразования каждой категориальной переменной в DataFrame в числовую переменную:

#identify all categorical variables cat_columns = df.select_dtypes(['object']).columns #convert all categorical variables to numeric df[cat_columns] = df[cat_columns].apply ( lambda x: pd.factorize (x)[ 0 ]) 

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1. Преобразование одной категориальной переменной в числовую

Предположим, у нас есть следующие Pandas DataFrame:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team position points rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 B G 9 6 4 B F 12 6 5 B C 9 5 6 C G 9 9 7 C F 4 12 8 C C 13 10 

Мы можем использовать следующий синтаксис для преобразования столбца «команда» в числовой:

#convert 'team' column to numeric df['team'] = pd.factorize(df['team'])[ 0 ] #view updated DataFrame df team position points rebounds 0 0 G 5 11 1 0 G 7 8 2 0 F 7 10 3 1 G 9 6 4 1 F 12 6 5 1 C 9 5 6 2 G 9 9 7 2 F 4 12 8 2 C 13 10 

Вот как работало преобразование:

  • Каждая команда со значением ‘ A ‘ была преобразована в 0 .
  • Каждая команда со значением « B » была преобразована в 1 .
  • Каждая команда со значением ‘ C ‘ была преобразована в 2 .

Пример 2. Преобразование нескольких категориальных переменных в числовые

Еще раз предположим, что у нас есть следующий кадр данных pandas:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team position points rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 B G 9 6 4 B F 12 6 5 B C 9 5 6 C G 9 9 7 C F 4 12 8 C C 13 10 

Мы можем использовать следующий синтаксис для преобразования каждой категориальной переменной в DataFrame в числовую переменную:

#get all categorical columns cat_columns = df.select_dtypes(['object']).columns #convert all categorical columns to numeric df[cat_columns] = df[cat_columns].apply ( lambda x: pd.factorize (x)[ 0 ]) #view updated DataFrame df team position points rebounds 0 0 0 5 11 1 0 0 7 8 2 0 1 7 10 3 1 0 9 6 4 1 1 12 6 5 1 2 9 5 6 2 0 9 9 7 2 1 4 12 8 2 2 13 10 

Обратите внимание, что два категориальных столбца (команда и позиция) были преобразованы в числовые, а столбцы очков и подборов остались прежними.

Примечание.Полную документацию по функции factorize() можно найти здесь .

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:

Источник

Как преобразовать категориальную переменную в числовую в Pandas

Вы можете использовать следующий базовый синтаксис для преобразования категориальной переменной в числовую переменную в кадре данных pandas:

df['column_name'] = pd.factorize(df['column_name'])[0] 

Вы также можете использовать следующий синтаксис для преобразования каждой категориальной переменной в DataFrame в числовую переменную:

#identify all categorical variables cat_columns = df.select_dtypes(['object']).columns #convert all categorical variables to numeric df[cat_columns] = df[cat_columns].apply ( lambda x: pd.factorize (x)[ 0 ]) 

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1. Преобразование одной категориальной переменной в числовую

Предположим, у нас есть следующие Pandas DataFrame:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team position points rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 B G 9 6 4 B F 12 6 5 B C 9 5 6 C G 9 9 7 C F 4 12 8 C C 13 10 

Мы можем использовать следующий синтаксис для преобразования столбца «команда» в числовой:

#convert 'team' column to numeric df['team'] = pd.factorize(df['team'])[ 0 ] #view updated DataFrame df team position points rebounds 0 0 G 5 11 1 0 G 7 8 2 0 F 7 10 3 1 G 9 6 4 1 F 12 6 5 1 C 9 5 6 2 G 9 9 7 2 F 4 12 8 2 C 13 10 

Вот как работало преобразование:

  • Каждая команда со значением ‘ A ‘ была преобразована в 0 .
  • Каждая команда со значением « B » была преобразована в 1 .
  • Каждая команда со значением ‘ C ‘ была преобразована в 2 .

Пример 2. Преобразование нескольких категориальных переменных в числовые

Еще раз предположим, что у нас есть следующий кадр данных pandas:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team position points rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 B G 9 6 4 B F 12 6 5 B C 9 5 6 C G 9 9 7 C F 4 12 8 C C 13 10 

Мы можем использовать следующий синтаксис для преобразования каждой категориальной переменной в DataFrame в числовую переменную:

#get all categorical columns cat_columns = df.select_dtypes(['object']).columns #convert all categorical columns to numeric df[cat_columns] = df[cat_columns].apply ( lambda x: pd.factorize (x)[ 0 ]) #view updated DataFrame df team position points rebounds 0 0 0 5 11 1 0 0 7 8 2 0 1 7 10 3 1 0 9 6 4 1 1 12 6 5 1 2 9 5 6 2 0 9 9 7 2 1 4 12 8 2 2 13 10 

Обратите внимание, что два категориальных столбца (команда и позиция) были преобразованы в числовые, а столбцы очков и подборов остались прежними.

Примечание.Полную документацию по функции factorize() можно найти здесь .

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:

Источник

How to convert categorical data to numerical data? [duplicate]

I have feature => city which is categorical data i.e string but instead of hardcoding using replace() is there any smart approach ?

train['city'].unique() Output: ['city_149', 'city_83', 'city_16', 'city_64', 'city_100', 'city_21', 'city_114', 'city_103', 'city_97', 'city_160', 'city_65', 'city_90', 'city_75', 'city_136', 'city_159', 'city_67', 'city_28', 'city_10', 'city_73', 'city_76', 'city_104', 'city_27', 'city_30', 'city_61', 'city_99', 'city_41', 'city_142', 'city_9', 'city_116', 'city_128', 'city_74', 'city_69', 'city_1', 'city_176', 'city_40', 'city_123', 'city_152', 'city_165', 'city_89', 'city_36', . ] 
train.replace(['city_149', 'city_83', 'city_16', 'city_64', 'city_100', 'city_21', 'city_114', 'city_103', 'city_97', 'city_160', 'city_65', 'city_90', 'city_75', 'city_136', 'city_159', 'city_67', 'city_28', 'city_10', 'city_73', 'city_76', 'city_104', 'city_27', 'city_30', 'city_61', 'city_99', 'city_41', 'city_142', 'city_9', 'city_116', 'city_128', 'city_74', 'city_69', 'city_1', 'city_176', 'city_40', 'city_123', 'city_152', 'city_165', 'city_89', 'city_36', . ], [1,2,3,4,5,6,7,8,9. ], inplace=True) 

Is there any better way to convert the data into numerical ? Because the number of unique values are 123 . So I need to hard code numbers from 1,2,3,4. 123 to convert it. Suggest some better way to convert it into numerical value.

Источник

pandas get mapping of categories to integer value

I can transform categorical columns to their categorical code but how do i get an accurate picture of their mapping? Example:

df_labels = pd.DataFrame() df_labels['col2'] = df_labels['col2'].astype('category') 
 col1 col2 0 1 a 1 2 b 2 3 c 3 4 a 4 5 b 

How do i get an accurate mapping of the cat codes to cat categories? The stackoverflow response below says to enumerate the categories. However, I’m not sure if enumerating was the way cat.codes generated the integer values. Is there a more accurate way? Get mapping of categorical variables in pandas

>>> dict( enumerate(df.five.cat.categories) )

FYI, I have since updated my answer (which you linked to) and added some explanation/verification. I believe it is accurate although I’m happy to improve it if you can elaborate about what you think is inaccurate about it.

4 Answers 4

Edited answer (removed cat.categories and changed list to dict ):

>>> dict(zip(df_labels.col2.cat.codes, df_labels.col2))

The original answer which some of the comments are referring to:

>>> list(zip(df_labels.col2.cat.codes, df_labels.col2.cat.categories)) [(0, 'a'), (1, 'b'), (2, 'c')] 

As the comments note, the original answer works in this example because the first three values happend to be [a,b,c] , but would fail if they were instead [c,b,a] or [b,c,a] .

Yes thanks! needed to put set in the front as i just want the unique mappings: set(list(zip(df_labels.col2.cat.codes, df_labels.col2.cat.categories)))

I think this answer only works because of the way col2 is ordered. len(cat.categories) is 3 while len(cat.codes) is 5.

This is an incorrect answer, because ser.cat.categories will return all the unique values in the category but not the corresponding label of the items in the series.

Thanks, @boud, I edited it (while preserving the original with a note). Please add additional edits as you see fit.

dict([(category, code) for code, category in enumerate(df_labels.col2.cat.categories)]) #

Note that this is roughly equivalent to the answer rejected by the OP: dict(enumerate(df.five.cat.categories)) except that it switches keys and values from e.g. 0:’a’ to ‘a’:0 which is a minor difference as both keys and values here are unique so the key/value order is in some sense irrelevant and it’s also easy enough to reverse. (I think the answer (mine!) rejected by the OP is actually correct so I also think this one is correct too!)

If you want to convert each column/ data series from categorical back to original, you just need to reverse what you did in the for loop of the dataframe. There are two methods to do that:

  1. To get back to the original Series or numpy array, use Series.astype(original_dtype) or np.asarray(categorical) .
  2. If you have already codes and categories, you can use the from_codes() constructor to save the factorize step during normal constructor mode.

Usage of from_codes

As on official documentation, it makes a Categorical type from codes and categories arrays.

splitter = np.random.choice([0,1], 5, p=[0.5,0.5]) s = pd.Series(pd.Categorical.from_codes(splitter, categories=["train", "test"])) print splitter print s 
[0 1 1 0 0] 0 train 1 test 2 test 3 train 4 train dtype: category Categories (2, object): [train, test] 
# after your previous conversion print df['col2'] # apply from_codes, the 2nd argument is the categories from mapping dict s = pd.Series(pd.Categorical.from_codes(df['col2'], list('abcde'))) print s 
0 0 1 1 2 2 3 0 4 1 Name: col2, dtype: int8 0 a 1 b 2 c 3 a 4 b dtype: category Categories (5, object): [a, b, c, d, e] 

Then you can easily construct the map by yourself using codes and categories. Yet you cannot maintain the order by a Python dictionary, use two lists or a list of tuples in @Boud answer instead.

OP asks for something «accurate» relative to the answer in the linked question:

dict(enumerate(df_labels.col2.cat.categories)) #

I believe that the above answer is indeed accurate (full disclosure: it is my answer in the other question that I’m defending). Note also that it is roughly equivalent to @pomber’s answer, except that the ordering of the keys and values is reversed. (Since both keys and values are unique, the ordering is in some sense irrelevant, and easy enough to reverse as a consequence).

However, the following way is arguably safer, or at least more transparent as to how it works:

dict(zip(df_labels.col2.cat.codes, df_labels.col2)) #

This is similar in spirit to @boud’s answer, but corrects an error by replacing df_labels.col2.cat.codes with df_labels.col2 . It also replaces list() with dict() which seems more appropriate for a mapping and automatically gets rid of duplicates.

Note that the length of both arguments to zip() is len(df) , whereas the length of df_labels.col2.cat.categories is a count of unique values which will generally be much shorter than len(df) .

Also note that this method is quite inefficient as it maps 0 to ‘a’ twice, and similarly for ‘b’ . In large dataframes the difference in speed could be pretty big. But it won’t cause any error because dict() will remove redundancies like this — it’s just that it will be much less efficient than the other method.

Источник

Читайте также:  Python get filename and extension
Оцените статью