Introduction
Using categorical type helps pandas store and work with repeated text data more efficiently. It saves memory and speeds up some operations.
Using categorical type helps pandas store and work with repeated text data more efficiently. It saves memory and speeds up some operations.
df['column'] = df['column'].astype('category')
df['color'] = df['color'].astype('category')
df['size'] = pd.Categorical(df['size'], categories=['small', 'medium', 'large'], ordered=True)
This code shows how converting a text column to categorical reduces memory use and lists the categories.
import pandas as pd # Create a sample DataFrame data = {'color': ['red', 'blue', 'red', 'green', 'blue', 'blue']} df = pd.DataFrame(data) # Show memory usage before mem_before = df.memory_usage(deep=True).sum() # Convert 'color' to categorical df['color'] = df['color'].astype('category') # Show memory usage after mem_after = df.memory_usage(deep=True).sum() print(f"Memory before: {mem_before} bytes") print(f"Memory after: {mem_after} bytes") # Show categories print(f"Categories: {df['color'].cat.categories.tolist()}")
Categorical columns use less memory because pandas stores the text once and uses codes internally.
Operations like grouping or sorting can be faster with categorical data.
Be careful when adding new categories; you may need to update the category list.
Categorical type saves memory for repeated text data.
It can speed up some data operations.
You can set an order for categories if needed.
categorical data type in pandas helpful when you have a column with many repeated text values?df['color'] to categorical type?astype() method is used to change data types in pandas.astype() converts the column to categorical type.import pandas as pd
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
df = pd.DataFrame({'color': colors})
df['color'] = df['color'].astype('category')
print(df['color'].cat.codes.tolist())df['size'] = ['small', 'medium', 'large', 'medium']
df['size'] = df['size'].astype('category')
df['size'] = df['size'].cat.set_categories(['small', 'medium', 'large'], ordered=True)
print(df['size'].sort_values())set_categories doessort_values() sorts rows, not the category levels themselves.set_categories method does not sort the data. -> Option A'city' containing many repeated city names. You want to reduce memory usage and speed up filtering for cities in a specific order: 'New York', 'Los Angeles', 'Chicago'. Which approach is best?Pass the test and this pattern moves unknown