Type Conversion

Nerd Cafe

What is Type Conversion in Python?

Type Conversion is the process of converting the data from one data type to another.

There are two types of type conversion:

  1. Implicit Type Conversion – Python automatically converts.

  2. Explicit Type Conversion – You manually convert.

Why It’s Important in Machine Learning?

In machine learning, you:

  • Read data from files (like CSVs) – everything might be a string.

  • Need to feed numbers (not strings) into models.

  • Often convert data types to fit into numpy arrays, pandas DataFrames, or scikit-learn models.

1. Implicit Type Conversion (Automatic by Python)

Python automatically converts smaller data types to larger data types during operations.

Example:

x = 5      # int
y = 2.0    # float

result = x + y
print(result)       # Output: 7.0
print(type(result)) # Output: <class 'float'>

Notes:

  • int + float = float

  • Useful in calculations – Python promotes to the higher precision type.

2. Explicit Type Conversion (Manual by You)

You manually convert using functions like:

Function
Converts To

int()

Integer

float()

Float

str()

String

bool()

Boolean

list()

List

Real-world Example in Machine Learning:

You read CSV data, and you get this:

But ML models need numeric types:

3. Practical Examples of int(), float(), str(), bool()

Convert String to Integer

But this will fail:

Solution:

Convert String to Float

Convert Number to String

Convert Boolean

Note: Empty string or zero = False. Everything else = True.

Use Case in Machine Learning: pandas

Important: Use .astype() to convert entire pandas column.

Type Conversion in NumPy

Example Project: Cleaning Data for ML

Tip: Check Before Converting

Always check the type before and after conversion:

Summary Cheat Sheet

ML Case You’ll Use Often

Scenario
Conversion Required

Data from CSV as strings

int(), float()

Encode categorical features

str to int (LabelEncoder)

Convert labels to booleans

strbool()

Pandas columns conversion

.astype(dtype)

NumPy array conversion

astype(dtype)

Keywords

type conversion, python casting, implicit conversion, explicit conversion, int(), float(), str(), bool(), list(), tuple(), data preprocessing, machine learning, pandas astype, numpy astype, data cleaning, csv parsing, type checking, value error, string to number, boolean conversion, nerd cafe

Last updated