NumPy · exercise

Net Promoter Score

Use boolean masks to turn a file of survey answers into one number.

Problem

Find the Net Promoter Score of this company.

Net Promoter Score equals the percentage of promoters (scores 9 and 10) minus the percentage of detractors (scores 0 to 6); 7 and 8 are passives

        import numpy as np
        url = ("https://raw.githubusercontent.com/hamzamohdzubair/"
               "small-data/refs/heads/main/nps.txt")
        data = np.loadtxt(url)
      

Solution


          total = data.shape[0]
          detractors = data[data<7].shape[0]
          promoters = data[data>8].shape[0]
          perc_promoters = (promoters/total)*100
          perc_detractors = (detractors/total)*100
          nps = perc_promoters - perc_detractors
        
< 7 detractors
7–8 passives
> 8 promoters
Shown on a made-up sample of 20 answers; the real file works the same way.

What we used

data < 7

A comparison makes a boolean mask, one True/False per answer.

data[mask]

Keeps only the True positions.

.shape[0]

Counts what is left. ((data < 7).sum() also works: True counts as 1.)

Back to NumPy · see Array Fundamentals for masking.