Day 23: Python Basic Statistics


One of the interesting exercises for Python so far, I want to share my source code for the question I extracted from the online learning website. The datasets for heights and positions are pre-randomized from the website.

  • Convert heights and positions, which are regular lists, to numpy arrays. Call them np_heights and np_positions.
  • Extract all the heights of the goalkeepers. You can use a little trick here: use np_positions == 'GK' as an index for np_heights. Assign the result to gk_heights.
  • Extract all the heights of all the other players. This time use np_positions != 'GK' as an index for np_heights. Assign the result to other_heights.
  • Print out the median height of the goalkeepers using np.median(). Replace None with the correct code.
  • Do the same for the other players. Print out their median height. Replace None with the correct code.
# Import numpy
import numpy as np

# Convert positions and heights to numpy arrays: np_positions, np_heights
np_heights = np.array(heights)
np_positions = np.array(positions)

# Heights of the goalkeepers: gk_heights
gk_heights = np_heights[np_positions == 'GK']

# Heights of the other players: other_heights
other_heights = np_heights[np_positions != 'GK']

# Print out the median height of goalkeepers. Replace 'None'
print("Median height of goalkeepers: " + str(np.median(gk_heights)))

# Print out the median height of other players. Replace 'None'
print("Median height of other players: " + str(np.median(other_heights)))

The output of the above source code execution is,

Median height of goalkeepers: 188.0
Median height of other players: 181.0

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s