0 votes
in Python Pandas by
Explain Categorical data in Pandas?

1 Answer

0 votes
by
A Categorical data is defined as a Pandas data type that corresponds to a categorical variable in statistics. A categorical variable is generally used to take a limited and usually fixed number of possible values. Examples: gender, country affiliation, blood type, social class, observation time, or rating via Likert scales. All values of categorical data are either in categories or np.nan.

This data type is useful in the following cases:

It is useful for a string variable that consists of only a few different values. If we want to save some memory, we can convert a string variable to a categorical variable.

It is useful for the lexical order of a variable that is not the same as the logical order (?one?, ?two?, ?three?) By converting into a categorical and specify an order on the categories, sorting and min/max is responsible for using the logical order instead of the lexical order.

It is useful as a signal to other Python libraries because this column should be treated as a categorical variable.

Parameters-

val : [list-like] The values of categorical. categories : [index like] Unique categorization of the categories. ordered : [boolean] If false, then the categorical is treated as unordered. dtype : [CategoricalDtype] an instance. Error- ValueError :  If the categories do not validate. TypeError :  If an explicit ordered = True but categorical can't be sorted. Return- Categorical variable

Code :

# Python code explaining

# numpy.pandas.Categorical()

# importing libraries

import numpy as np

import pandas as pd

# Categorical using dtype

c = pd.Series([“a”, “b”, “d”, “a”, “d”], dtype =”category”)

print (“\nCategorical without pandas.Categorical() : \n”, c)

c1 = pd.Categorical([1, 2, 3, 1, 2, 3])

print (“\n\nc1 : “, c1)

c2 = pd.Categorical([‘e’, ‘m’, ‘f’, ‘i’,

‘f’, ‘e’, ‘h’, ‘m’ ])

print (“\nc2 : “, c2)

Related questions

0 votes
asked Aug 13, 2021 in Python Pandas by SakshiSharma
0 votes
asked Nov 9, 2021 in Python Pandas by Robin
...