I am trying to run some Machine learning algo on a dataset using scikit-learn. My dataset has some features which are like categories. Like one feature is A
, which has values 1,2,3
specifying the quality of something. 1:Upper, 2: Second, 3: Third class
. So it's an ordinal variable.
Similarly I re-coded a variable City
, having three values ('London', Zurich', 'New York'
into 1,2,3
but with no specific preference for the values. So now this is a nominal categorical variable.
How do I specify the algorithm to consider these as categorical and ordinal etc. in pandas?. Like in R, a categorical variable is specified by factor(a)
and hence is not considered a continuous value. Is there anything like that in pandas/python?
You should use the OneHotEncoder transformer with the categorical variables, and leave the ordinal variable untouched:
... years later (and because I think a good explanation of these issues is required not only for this question but to help remind myself in the future)
Ordinal vs. Nominal
In general, one would translate categorical variables into dummy variables (or a host of other methodologies), because they were nominal, e.g. they had no sense of
a > b > c
. In OPs original question, this would only be performed on the Cities, like London, Zurich, New York.Dummy Variables for Nominal
For this type of issue,
pandas
provides -- by far -- the easiest transformation usingpandas.get_dummies
. So:Ordinal Encoding for Categorical Variables
However in the case of ordinal variables, the user must be cautious in using
pandas.factorize
. The reason is that the engineer wants to preserve the relationship in the mapping such thata > b > c
.So if I want to take a set of categorical variables where
large > medium > small
, and preserve that, I need to make sure thatpandas.factorize
preserves that relationship.In fact, the relationship that needs to be preserved in order to maintain the concept of ordinal has been lost using
pandas.factorize
. In an instance like this, I use my own mappings to ensure that the ordinal attributes are preserved.In fact, by creating your own
dict
to map the values is a way to not only preserve your desired ordinal relationship but also can be used as "keeping the contents and mappings of your prediction algorithm organized" ensuring that not only have you not lost any ordinal information in the process, but also have stored records of what each mapping for each variable is.int
s intosklearn
Lastly, the OP spoke about passing the information into
scikit-lean
classifiers, which means thatint
s are required. For that case, make sure you're aware of theastype(int)
gotcha that is detailed here if you have anyNaN
s in your data.See https://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html and see this question How to reformat categorical Pandas variables for Sci-kit Learn