Numpy arrays are similar to Python lists, but they are more powerful and efficient, especially for working with large datasets. Arrays can be created using the numpy.array() function, which takes a list as input and returns a numpy array.


# Create 2 new lists height and weight
height = [1.87,  1.87, 1.82, 1.91, 1.90, 1.85]
weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]

# Import the numpy package as np
import numpy as np

# Create 2 numpy arrays from height and weight
np_height = np.array(height)
np_weight = np.array(weight)

print(type(np_height))

print(type(np_height))

Numpy arrays have several advantages over Python lists. First, they are more memory-efficient since they store data in contiguous blocks of memory. This makes it easier and faster to perform operations on large datasets. Second, numpy arrays support vectorized operations, which allows you to perform operations on entire arrays at once. This can significantly speed up calculations and simplify code.


# Calculate bmi
bmi = np_weight / np_height ** 2

# Print the result
print(bmi)

Numpy arrays also support many useful operations and methods, such as slicing, indexing, reshaping, and concatenation. These operations allow you to manipulate arrays and extract information from them in a flexible and efficient way.


# For a boolean response
bmi > 23

# Print only those observations above 23
bmi[bmi > 23]

One of the most powerful features of numpy arrays is their ability to perform mathematical operations and calculations. Numpy provides a wide range of mathematical functions, such as sin(), cos(), exp(), and log(), which can be applied to arrays element-wise. This allows you to perform complex mathematical calculations on large datasets with ease.

Numpy Arrays Exercise Solution


#Code Completed
weight_kg = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]

import numpy as np

# Create a numpy array np_weight_kg from weight_kg
np_weight_kg = np.array(weight_kg)

# Create np_weight_lbs from np_weight_kg
np_weight_lbs = np_weight_kg * 2.2

# Print out np_weight_lbs
print(np_weight_lbs)

In summary, numpy arrays are an essential tool for scientific computing and data analysis in Python. They provide a powerful and efficient way to store and manipulate data, and support a wide range of mathematical operations and functions. By using numpy arrays, you can build robust and scalable applications that process and analyze large datasets with ease.