Category
Pandas provides the category
data type, which is analogous to the R factor.
You can convert a column into a categorical data type by passing 'category'
to the .astype()
method.
Once you have a categorical column, you can see the various categories (known as levels in R) by using the .cat
accessor and calling the .categories
attribute.
Another use case for categorical values is when you want to preserve ordering in your data.
For example, intuitively it makes sense that 'low' comes before 'high'. You can use reorder_categories()
to provide an order to a column.
# Reorder categorical levels
df['column_name'].cat.reorder_categories(['low', 'high'], ordered=True)
Este exercício faz parte do curso
Python for R Users
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# Convert the type of time column
tips['time'] = ____
# Use the cat accessor to print the categories in the time column
print(____)