Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

Data Type Conversion and Casting

Learn how to convert NumPy arrays between integer, floating-point, Boolean, and string data types. Understand astype(), explicit dtype selection, type promotion, precision, and safe data handling.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand data type conversion in NumPy.
  • Convert arrays using the astype() method.
  • Convert integers to floating-point values.
  • Convert floating-point values to integers.
  • Convert numeric arrays to Boolean and string types.
  • Specify data types during array creation.
  • Understand type promotion in arithmetic operations.
  • Identify precision loss and possible conversion errors.
  • Inspect an array's dtype before and after conversion.
  • Apply data type conversion to practical datasets.
Beginner tip: Use astype() when you want to create a converted array. Always inspect the resulting dtype and check whether conversion changes the original values.

2. What Is Data Type Conversion?

Data type conversion is the process of changing how values are represented in an array. For example, an integer array can be converted into a floating-point array to support decimal values.

NumPy provides the astype() method for converting array elements to a requested data type. Conversion is useful when preparing datasets, performing calculations, and managing memory.

Example: Converting Integers to Floats

import numpy as np numbers = np.array([10, 20, 30, 40]) float_numbers = numbers.astype(np.float64) print(numbers) print(numbers.dtype) print(float_numbers) print(float_numbers.dtype)

Output

[10 20 30 40] int64 [10. 20. 30. 40.] float64

The converted array stores the values using a floating-point data type. The original array remains unchanged.

Data Type Conversion Integer Array Floating-Point Array 10 20 30 40 10. 20. 30. 40. astype(np.float64) Values are converted; the original array is not modified.
Figure 1: The astype() method creates a converted array with the requested data type.

3. Using astype() to Convert Data Types

The astype() method accepts a target data type and returns a new array containing converted values.

import numpy as np values = np.array([5, 10, 15, 20]) as_float = values.astype(np.float32) as_int64 = values.astype(np.int64) as_text = values.astype(str) print(as_float, as_float.dtype) print(as_int64, as_int64.dtype) print(as_text, as_text.dtype)

Common Conversion Targets

Target Type Example Typical Purpose
np.int32 values.astype(np.int32) Store whole-number values using a 32-bit integer type.
np.float32 values.astype(np.float32) Represent values using 32-bit floating-point numbers.
np.float64 values.astype(np.float64) Use 64-bit floating-point representation.
np.bool_ values.astype(np.bool_) Convert values to Boolean representations.
str values.astype(str) Convert values to strings.
Remember: astype() returns a new array by default. Assign the result to a variable if you want to use the converted values later.

4. Converting Floating-Point Values to Integers

Floating-point arrays can be converted to integer arrays. For finite floating-point values, the fractional part is discarded during conversion to an integer type.

import numpy as np prices = np.array([12.8, 25.4, 37.9, 49.2]) whole_prices = prices.astype(np.int32) print(prices) print(whole_prices)

Output

[12.8 25.4 37.9 49.2] [12 25 37 49]

The conversion does not round the values to the nearest integer. For example, 12.8 becomes 12 rather than 13.

Conversion vs. Rounding

values = np.array([12.8, 25.4, 37.9]) converted = values.astype(np.int32) rounded = np.round(values) print(converted) # Output: [12 25 37] print(rounded) # Output: [13. 25. 38.]

Use astype() when you need a type conversion. Use np.round() when you want to round numerical values.

Important: Converting floating-point values to integers can lose fractional information. Keep the original values if you need the decimal precision for later calculations.

5. Converting Integers to Floating-Point Values

Integer values can be converted to floating-point values when decimal calculations are required. The conversion represents the integer values using a floating-point data type.

import numpy as np marks = np.array([78, 85, 92, 67]) decimal_marks = marks.astype(np.float64) print(decimal_marks) print(decimal_marks.dtype) average = decimal_marks.mean() print("Average:", average)

Output

[78. 85. 92. 67.] float64 Average: 80.5

Floating-point conversion is useful when a calculation involves decimal values, although NumPy's arithmetic operations may already promote types when required.

Practical tip: Choose a floating-point type that provides sufficient precision for the calculation. Converting to float32 uses less element memory than float64, but generally provides less precision.

6. Converting Numeric Values to Boolean

NumPy's Boolean type is represented by np.bool_. When ordinary numeric values are converted to Boolean values, zero becomes False and nonzero values become True.

import numpy as np values = np.array([0, 1, 2, 0, -5]) boolean_values = values.astype(np.bool_) print(boolean_values) # Output: [False True True False True]

Boolean Conversion Rules

Numeric Value Boolean Result
0 False
1 True
25 True
-3 True
Important: Converting a number to Boolean does not test whether the number meets a particular business rule. If you want to identify positive values, use a comparison such as values > 0.

7. Converting Values to Strings

Numeric arrays can be converted to string arrays using astype(str). This is useful when preparing values for text-based output or certain reporting tasks.

import numpy as np numbers = np.array([100, 200, 300]) text_numbers = numbers.astype(str) print(text_numbers) print(text_numbers.dtype) print(text_numbers[0]) print(type(text_numbers[0]))

The resulting elements are strings rather than numeric values. Arithmetic operations that require numbers may therefore behave differently or fail until the values are converted back.

Converting Numeric Text Back to Numbers

text_values = np.array(["10", "20", "30"]) integer_values = text_values.astype(np.int32) float_values = text_values.astype(np.float64) print(integer_values) print(float_values)
Important: Text must contain values that can be parsed as the requested numeric type. Invalid strings such as "hello" cannot be converted directly to an integer or floating-point value using ordinary astype() conversion.

8. Specifying a Data Type During Array Creation

Instead of converting an existing array later, you can specify a target data type while creating an array using the dtype parameter.

import numpy as np integers = np.array([10, 20, 30], dtype=np.int32) decimals = np.array([10, 20, 30], dtype=np.float64) flags = np.array([1, 0, 1], dtype=np.bool_) print(integers, integers.dtype) print(decimals, decimals.dtype) print(flags, flags.dtype)

When to Use dtype and astype()

Method Example Use Case
dtype parameter np.array([1, 2], dtype=np.float32) Choose the type when creating an array.
astype() array.astype(np.float32) Convert an existing array to another type.
Remember: Use dtype during construction when you already know the desired type. Use astype() when you need to convert an existing array.

9. Understanding Type Promotion

NumPy may promote values to a common data type when arrays of different types are combined in an operation. This helps represent the result appropriately.

import numpy as np integers = np.array([1, 2, 3], dtype=np.int32) decimals = np.array([0.5, 1.5, 2.5], dtype=np.float64) result = integers + decimals print(result) print(result.dtype)

Output

[1.5 3.5 5.5] float64

In this example, the result uses a floating-point data type to represent the decimal values. The precise result type depends on the input types and the operation being performed.

values = np.array([10, 20, 30], dtype=np.int32) result = values / 2 print(result) print(result.dtype)

NumPy's true-division operation generally produces floating-point results even when the inputs are integers.

Practical tip: Inspect the resulting dtype after arithmetic operations if the data type is important to your application.

10. Precision, Range, and Safe Conversion

Different data types support different numerical ranges and precision levels. Selecting an unsuitable type can lead to information loss or unexpected results.

import numpy as np values = np.array([12.75, 24.50, 36.25]) as_float32 = values.astype(np.float32) as_int32 = values.astype(np.int32) print(as_float32) print(as_int32)

Common Conversion Risks

Conversion Possible Risk Recommended Check
Float to integer Fractional parts are discarded. Check whether decimal precision is required.
Large integer to smaller integer Values may not fit in the target range. Check the target type's supported range.
Float64 to float32 Precision may be reduced. Compare the precision requirements.
String to numeric Invalid text may cause conversion errors. Validate the input strings first.
Numeric to Boolean Nonzero values all become True. Use a comparison when a specific condition is needed.
Important: A successful conversion does not guarantee that all original information has been preserved. Always verify the converted values when precision matters.

11. Common Data Type Conversion Errors

Problem Reason Solution
Invalid string conversion The source text cannot be parsed as the target type. Validate and clean text before conversion.
Unexpected loss of decimals Floating-point values were converted to integers. Use a floating-point target type if decimals are required.
Unexpected Boolean results Every nonzero number converts to True. Use a comparison for the intended condition.
Insufficient integer range The target integer type cannot represent all values. Choose an appropriate integer type.
Unexpected output dtype NumPy promoted the input types during an operation. Inspect the resulting dtype.
Debugging tip: Print the source dtype, target dtype, and converted values to understand how a conversion affects the array.
values = np.array([10.8, 20.4, 30.9]) converted = values.astype(np.int32) print("Original dtype:", values.dtype) print("Converted dtype:", converted.dtype) print("Original values:", values) print("Converted values:", converted)

12. Practical Activity: Student Marks Conversion

Activity: Convert and Analyze Marks

Samiksha is preparing student marks for numerical analysis. Convert integer marks to floating-point values, calculate the average, and compare the original and converted arrays.

import numpy as np marks = np.array([78, 85, 92, 67, 88], dtype=np.int32) print("Original marks:", marks) print("Original dtype:", marks.dtype) decimal_marks = marks.astype(np.float64) print("Converted marks:", decimal_marks) print("Converted dtype:", decimal_marks.dtype) print("Average marks:", decimal_marks.mean()) whole_marks = np.array([78.8, 85.4, 92.9]).astype(np.int32) print("Converted whole marks:", whole_marks)

Expected Output

Original marks: [78 85 92 67 88] Original dtype: int32 Converted marks: [78. 85. 92. 67. 88.] Converted dtype: float64 Average marks: 82.0 Converted whole marks: [78 85 92]

This activity demonstrates how to convert data types, inspect the resulting dtype, calculate an average, and recognize the loss of fractional parts during integer conversion.

13. Practice Exercises

Use the following arrays to complete the exercises:

import numpy as np values = np.array([10, 20, 30, 40]) prices = np.array([12.8, 25.4, 37.9, 49.2]) text_values = np.array(["10", "20", "30"])
  1. Convert the values array to float64.
  2. Convert the prices array to int32 and observe the fractional parts.
  3. Convert the values array to strings.
  4. Convert the numeric text values to integers.
  5. Convert the numeric array [0, 1, 2, 0] to Boolean values.
  6. Create an array using dtype=np.float32.
  7. Print the dtype before and after each conversion.
  8. Explain the difference between astype() and the dtype parameter.

Challenge Exercise

Pradnya is preparing a sales dataset containing integer quantities and decimal prices. Write a program that:

  • Creates an integer array for product quantities.
  • Creates a floating-point array for product prices.
  • Converts the quantities to float32.
  • Calculates the total price for each product.
  • Inspects the resulting dtype.
  • Explains why converting prices to integers may lose information.
Practice goal: Always compare the original values and the converted values so you can identify changes caused by type conversion.

Summary

In this lesson, we learned how to convert NumPy arrays using astype() and how to specify data types when creating arrays.

We converted integer values to floating-point values, converted floating-point values to integers, and explored Boolean and string conversions. We also learned about type promotion, numerical precision, supported ranges, and common conversion errors. These concepts help maintain data quality during numerical processing. Practice converting arrays and checking the resulting dtype before using the converted values in calculations.