Menu

Creating and Accessing NumPy Arrays

Creating and Accessing NumPy Arrays

NumPy offers several functions for creating arrays, depending on the type of data you need.

Using Built-in Array Creation Functions

import numpy as np

zeros = np.zeros(4)

ones = np.ones(3)

sequence = np.arange(1, 10, 2)

evenly_spaced = np.linspace(0, 1, 5)

print(zeros)

print(ones)

print(sequence)

print(evenly_spaced)

  • np.zeros() creates an array filled with zeros.
  • np.ones() creates an array filled with ones.
  • np.arange() generates values using a start, stop, and step.
  • np.linspace() generates a specified number of evenly spaced values across an interval.

These functions are useful for initializing calculations, generating numerical sequences, and preparing sample data.

Accessing and Slicing Elements

NumPy uses zero-based indexing, just like Python lists.

import numpy as np

temperatures = np.array([28, 31, 29, 35, 32, 30])

print(temperatures[0])     # First element

print(temperatures[-1])    # Last element

print(temperatures[1:4])   # Elements at indices 1, 2, and 3

You can also access specific elements in a two-dimensional array using row and column indices.

matrix = np.array([

[10, 20, 30],

[40, 50, 60],

[70, 80, 90]

])

print(matrix[0, 1])  # 20

print(matrix[2, 2])  # 90

print(matrix[:, 0])  # First column

In matrix[:, 0], the colon selects every row, while 0 selects the first column. This is especially useful when extracting individual features from numerical datasets.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details