Using the right data types helps your computer work faster and use less memory when handling data.
Using appropriate dtypes in Pandas
df = df.astype({'column_name': 'dtype'})You can change one or many columns at once by passing a dictionary.
Common dtypes include 'int', 'float', 'category', and 'bool'.
df['age'] = df['age'].astype('int')
df = df.astype({'gender': 'category', 'income': 'float'})df['is_student'] = df['is_student'].astype('bool')
This code creates a table with all columns as text. Then it changes each column to a better type: numbers to int or float, categories to category type, and true/false to boolean.
import pandas as pd # Create a sample DataFrame data = {'age': ['25', '30', '22', '40'], 'gender': ['M', 'F', 'F', 'M'], 'income': ['50000', '60000', '45000', '80000'], 'is_student': ['False', 'True', 'False', 'False']} df = pd.DataFrame(data) print('Before changing dtypes:') print(df.dtypes) # Change dtypes to appropriate types df = df.astype({'age': 'int', 'gender': 'category', 'income': 'float', 'is_student': 'bool'}) print('\nAfter changing dtypes:') print(df.dtypes)
Using 'category' for columns with few unique values saves memory and speeds up operations.
Be careful: converting to wrong dtype can cause errors or data loss.
Use df.info() to check memory usage before and after changing dtypes.
Choosing the right data type makes your data smaller and faster to work with.
You can change data types easily with the astype() method.
Check your data types often to keep your data clean and efficient.
Practice
Solution
Step 1: Understand data types impact on memory
Using smaller or correct data types reduces the memory needed to store data.Step 2: Understand data types impact on speed
Operations on smaller data types run faster, improving performance.Final Answer:
It reduces memory usage and speeds up data processing. -> Option BQuick Check:
Appropriate dtypes = less memory and faster [OK]
- Thinking data types change data values automatically
- Believing data types affect DataFrame colors
- Assuming data types reorder rows
age to integer type in pandas?Solution
Step 1: Recall pandas syntax for changing dtype
The correct method is to useastype()on the column.Step 2: Check method usage
Usedf['age'] = df['age'].astype('int')to convert the 'age' column to integer.Final Answer:
df['age'] = df['age'].astype('int') -> Option AQuick Check:
astype() method changes dtype [OK]
- Forgetting to assign the result of astype() back to the column
- Using non-existent methods like convert() or change_type()
- Passing arguments in wrong order or syntax
df.dtypes?
import pandas as pd
data = {'score': [90, 85, 88], 'passed': ['True', 'False', 'True']}
df = pd.DataFrame(data)
df['passed'] = df['passed'].astype('bool')
print(df.dtypes)Solution
Step 1: Check initial data types
'score' is a list of integers, so pandas infers int64. 'passed' is string initially.Step 2: Convert 'passed' to boolean
Usingastype('bool')converts 'passed' column to boolean type.Final Answer:
score int64 passed bool dtype: object -> Option CQuick Check:
astype('bool') converts string to bool [OK]
- Assuming 'passed' stays as object after astype('bool')
- Thinking 'score' becomes float automatically
- Confusing bool with string type
df['price'] = df['price'].astype('int64')
df['price'] = df['price'].astype('category')
Why might this cause an error or unexpected behavior?Solution
Step 1: Understand dtype conversion to category
Converting numeric to category is allowed but categories are based on unique values.Step 2: Consider memory and behavior risks
If the numeric column has many unique values, category conversion may increase memory or cause unexpected grouping.Final Answer:
Converting numeric to category without checking unique values may increase memory usage or cause unexpected behavior. -> Option AQuick Check:
Category dtype needs careful unique value check [OK]
- Thinking multiple astype() calls are invalid
- Believing astype('category') only works on strings
- Assuming int64 is invalid dtype
status containing only three unique string values: 'new', 'in_progress', 'done'. Which dtype change will save memory and keep data efficient?Solution
Step 1: Identify unique values in 'status'
Only three unique strings exist, ideal for categorical dtype.Step 2: Understand category dtype benefits
Category stores unique values once and uses integer codes internally, saving memory.Step 3: Compare other options
Object dtype stores full strings repeatedly; int64 conversion is invalid without mapping; no change wastes memory.Final Answer:
Convertstatustocategorydtype. -> Option DQuick Check:
Few unique strings? Use category dtype [OK]
- Trying to convert strings directly to int64 without mapping
- Keeping object dtype wastes memory
- Ignoring category dtype benefits
Ready to prove it?
Pass the test and this pattern moves unknown
