Python – How to find the average height of presidents from selected row numbers?

Question:

I am new to Python and trying to figure out how to pass two arguments that will correspond to the start and stop of a slice, respectively. It will slice the heights column in a csv file with president height.
Then print the average height, rounded to two decimals, of the selected presidents in the following form:

‘The average height of presidents number x to y is z’

I have to use sys and panda for this problem.

Some example of the csv file looks like this:

enter image description here

This is my code:

import sys
import pandas as pd
df= pd.read_csv("president_heights.csv")


def president_height(x,y):
    x = int(x)
    y = int(y)
    result = df.iloc[:x,y].mean(axis=0) 
    return result

x = sys.argv[1]
y = sys.argv[2]
result = president_height(x,y)
print(f'The average height of presidents number {x} to {y} is {result:.2f}')

The Expected output:
The average height of presidents number 4 to 10 is 177.17

Actual Output:
  IndexError: single positional indexer is out-of-bounds

I can’t figure out how to fix this. Please help!

Asked By: MCly

||

Answers:

You are not using the iloc[] correctly. The first argument refers to the rows, whereas the second to the columns therefore it works like: iloc[start-row:finish-row,start-column:finish-column].

Replace this line:

 result = df.iloc[:x,y].mean(axis=0) 

With:

 result = df.iloc[x:y,1].mean(axis=0) 
Answered By: Celius Stingher
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.