Home > Enterprise >  Python - How to find the average height of presidents from selected row numbers?
Python - How to find the average height of presidents from selected row numbers?

Time:08-09

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!

CodePudding user response:

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) 
  • Related