Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading