Contents

Python NumPy For Your Grandma | Section 2.2 | Creating NumPy Arrays

Contents

Course Contents

  1. Introduction
  2. NumPy Arrays
    2.1 What’s A NumPy Array
    2.2 Creating NumPy Arrays
    2.3 Indexing And Modifying 1-D Arrays
    2.4 Indexing And Modifying Multidimensional Arrays
    2.5 Basic Math
  3. Intermediate Array Stuff
    3.1 Broadcasting
    3.2 newaxis
    3.3 reshape
    3.4 boolean indexing
    3.5 nan
    3.6 infinity
    3.7 random
  4. Common Operations
    4.1 where
    4.2 Math Funcs
    4.3 all and any
    4.4 concatenate
    4.5 Stacking
    4.6 Sorting
    4.7 unique
  5. Challenges

This video covers various ways to create a NumPy array from scratch.

Code

import numpy as np

# from list
np.array(['a', 'b', 'c'])

# from list of lists
np.array([
    ['a', 'b'],
    ['c', 'd'],
    ['e', 'f']
])

# 3x5 array of 0s with np.zeros()
np.zeros(shape = (3, 5))


# initialize the array with any value
np.full(shape = (3, 5), fill_value = 'cat')

# sequence of integers from 1 to N
np.arange(start = 1, stop = 5, step = 1)  # note that start is inclusive while stop is exclusive

# random integers between 1 and 6
np.random.randint(low = 1, high = 7, size = (2, 3))

Transcript

There are many ways to create a numpy array from scratch. Here are some of the most common.

  1. As we saw earlier, you can make an array from a list
  2. You can make a 2-dimensional array from a list of lists
  3. You can use np.zeros() to make an array of 0s
  4. More generally, you can use np.full() to initialize an array of any shape, filled with a specific value
  5. You can use np.arange() to make an array as a sequence of integers from 1 to N. Note that the start parameter is inclusive but the stop parameter is exclusive.
  6. You can use np.random.randint() to make an array of random integers in some range

These are some of the most common ways to make an array, but there are lots of other methods. We’ll see more of them as we go through the course.