Sometimes data is not in the right form to work with. Changing data types helps fix this so we can analyze data correctly.
Changing data types (astype) in Data Analysis Python
new_data = old_data.astype(new_type)
astype() is a method used on pandas Series or DataFrames.
You can pass types like 'int', 'float', 'str', 'category', or numpy types.
df['age'] = df['age'].astype('int')
df['price'] = df['price'].astype('float')
df['date'] = pd.to_datetime(df['date']).astype('datetime64[ns]')
df['category'] = df['category'].astype('category')
This code shows how to convert columns from strings to proper types like int, float, and category. It prints the data types before and after the change.
import pandas as pd # Create a sample DataFrame with mixed types data = {'age': ['25', '30', '22'], 'price': ['10.5', '20.3', '15.0'], 'category': ['A', 'B', 'A']} df = pd.DataFrame(data) print('Before changing types:') print(df.dtypes) # Change 'age' to int s_age = df['age'].astype(int) # Change 'price' to float s_price = df['price'].astype(float) # Change 'category' to category type s_cat = df['category'].astype('category') # Assign back to DataFrame df['age'] = s_age df['price'] = s_price df['category'] = s_cat print('\nAfter changing types:') print(df.dtypes)
If conversion fails (like trying to convert 'abc' to int), astype() will raise an error.
Use pd.to_datetime() for date conversions before astype if needed.
Converting to 'category' can save memory when you have repeated text values.
Use astype() to change data types of pandas columns easily.
Correct data types help with accurate calculations and faster processing.
Always check data before converting to avoid errors.
Practice
astype() method do in pandas?Solution
Step 1: Understand the purpose of
Theastype()astype()method is used to convert the data type of a pandas Series or DataFrame column.Step 2: Compare with other options
Filtering, sorting, and merging are different pandas operations and not related to changing data types.Final Answer:
It changes the data type of a DataFrame column. -> Option BQuick Check:
astype()changes data types [OK]
- Confusing astype() with filtering or sorting methods
- Thinking astype() merges DataFrames
- Assuming astype() modifies values instead of types
'age' to integer type?Solution
Step 1: Recall correct method call syntax
Theastype()method is called on the Series object likedf['age'].astype(int).Step 2: Check other options for syntax errors
df.astype['age'](int) uses wrong bracket placement, C uses a non-existent method, and D uses wrong function call style.Final Answer:
df['age'].astype(int) -> Option DQuick Check:
Correct syntax is Series.astype(type) [OK]
- Using wrong brackets or parentheses
- Calling astype on DataFrame instead of Series
- Using non-existent methods like convert()
import pandas as pd
df = pd.DataFrame({'score': ['10', '20', '30']})
df['score'] = df['score'].astype(int)
print(df.dtypes)What will be the output?
Solution
Step 1: Understand the initial data type
The 'score' column starts as strings (object type) because values are in quotes.Step 2: Apply astype(int) conversion
Usingastype(int)converts the column to integer type, which pandas shows asint64.Step 3: Check the printed dtypes output
The output shows the column name and its type, followed by dtype info. The correct output is:
score int64
dtype: int64Final Answer:
score int64 dtype: int64 -> Option AQuick Check:
astype(int) converts to int64 dtype [OK]
- Expecting dtype to be 'object' after conversion
- Confusing dtype display format
- Thinking astype changes values, not type
astype(int)?Solution
Step 1: Understand what astype(int) expects
The method expects values that can be converted to integers, like numeric strings or numbers.Step 2: Consider non-numeric strings
If the column contains strings like 'abc', conversion to int is impossible and raises a ValueError.Step 3: Identify the error message
The error message is: ValueError: invalid literal for int() with base 10.Final Answer:
ValueError: invalid literal for int() with base 10 -> Option CQuick Check:
Non-numeric strings cause ValueError on astype(int) [OK]
- Expecting silent failure or automatic conversion
- Confusing ValueError with TypeError
- Thinking KeyError relates to conversion
'price' containing numbers as strings with dollar signs, like '$100', '$250'. How do you convert this column to float type for calculations?Solution
Step 1: Remove dollar signs from strings
Dollar signs prevent direct conversion to float. Usestr.replace('$', '')to remove them.Step 2: Convert cleaned strings to float
After removing '$', useastype(float)to convert the column to float type.Step 3: Check other options
df['price'] = df['price'].astype(float) tries to convert without removing '$' causing error. df['price'] = df['price'].replace('$', '').astype(float) usesreplacewithoutstraccessor, which won't work on strings. df['price'] = df['price'].astype(str).astype(float) converts to string again unnecessarily.Final Answer:
df['price'] = df['price'].str.replace('$', '').astype(float) -> Option AQuick Check:
Remove symbols first, then astype(float) [OK]
- Trying to convert strings with symbols directly
- Using replace without str accessor on strings
- Double converting types unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
