NumPy array basics

This recipe includes the following topics:

  • Create NumPy array
  • Access data
  • Basic operation

Create NumPy Array


# import NumPy module
import numpy as np

# create a Python list
temperatureList = [32, 68, 78, 110, 60, 28]

# create a NumPy array
temperatureArray = np.array(temperatureList)

# display content
print(temperatureArray)
[ 32  68  78 110  60  28]

Access data


# import NumPy module
import numpy as np

# create a Python list
temperatureList = [[32, 68], [78, 110], [60, 28]]

# create a 2D NumPy array
temperatureArray = np.array(temperatureList)

# display first row
print('First row: %s' % temperatureArray[0])

# display last row
print('Last row: %s' % temperatureArray[-1])

# display specific element
print("Specific row and col: %s" % temperatureArray[1, 1])
First row: [32 68]
Last row: [60 28]
Specific row and col: 110

Basic operation


# import NumPy module
import numpy as np

# create Python lists
temperatureList1 = [32, 68, 78]
temperatureList2 = [110, 60, 28]

# create NumPy arrays
temperatureArray1 = np.array(temperatureList1)
temperatureArray2 = np.array(temperatureList2)

# sum of two arrays
temperatureArraySum = temperatureArray1 + temperatureArray2

# display the sum
print("Addition: %s" % temperatureArraySum)

# smallest value
print("Smallest value: %s" % temperatureArray1.min())

# highest value
print("Highest value: %s" % temperatureArray1.max())

# mean value
print("Mean value: %s" % temperatureArray1.mean())
Addition: [142 128 106]
Smallest value: 32
Highest value: 78
Mean value: 59.333333333333336

Leave a Reply

Your email address will not be published. Required fields are marked *