# Python NumPy For Your Grandma - 4.8 Challenge: Movie Ratings

Contents

## Setup

You’re given a 10x2 array of floats where each row represents a movie. The first column represents the movie’s rating and the second column represents the director’s rating. Your goal is to create a third column to represent the overall rating. The overall rating is equal to the movie rating if it exists, otherwise it’s the director’s rating.

``````import numpy as np

generator = np.random.default_rng(123)
ratings = np.round(generator.uniform(low = 0.0, high = 10.0, size = (10, 2)))
ratings[[1,2,7,9], [0,0,0,0]] = np.nan
print(ratings)
## [[ 7.  1.]
##  [nan  2.]
##  [nan  8.]
##  [ 9.  3.]
##  [ 8.  9.]
##  [ 5.  2.]
##  [ 8.  2.]
##  [nan  6.]
##  [ 9.  2.]
##  [nan  5.]]
``````

## Solution 1

``````x = np.where(np.isnan(ratings[:, 0]), ratings[:, 1], ratings[:, 0])
result = np.insert(arr = ratings, values = x, axis = 1, obj = 2)
print(result)
## [[ 7.  1.  7.]
##  [nan  2.  2.]
##  [nan  8.  8.]
##  [ 9.  3.  9.]
##  [ 8.  9.  8.]
##  [ 5.  2.  5.]
##  [ 8.  2.  8.]
##  [nan  6.  6.]
##  [ 9.  2.  9.]
##  [nan  5.  5.]]
``````

## Solution 2

``````x = np.where(np.isnan(ratings[:, 0]), ratings[:, 1], ratings[:, 0])
result = np.hstack((ratings, x[:, None]))
print(result)
## [[ 7.  1.  7.]
##  [nan  2.  2.]
##  [nan  8.  8.]
##  [ 9.  3.  9.]
##  [ 8.  9.  8.]
##  [ 5.  2.  5.]
##  [ 8.  2.  8.]
##  [nan  6.  6.]
##  [ 9.  2.  9.]
##  [nan  5.  5.]]
``````