0

Here is the code I used to calculate average with numpy and pandas

def calc_average_books_stock():
    
  text_file = open('book_data_file.txt')
    
  values = []
    
  for index,data in df.iterrows():
        
    if int(data['STOCK']) > 0:
            
      values.append(data['COST?'])
    
      avg = np.mean(values)
    
      print(f"Average Book in Stock: {round(avg, 2)}")

I would like to know if there was a way to this without numpy and pandas and just be able to do it with python's standard library

1

2 Answers 2

1

do it with python's standard library You might use .mean from statistics built-in module to calculate average, for example:

import statistics
values = [10, 30, 20]
avg = statistics.mean(values)
print(avg)

output:

20
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not 100 sure of where df is coming from, but if your file is in some kind of CSV format, you can replace the pandas with csv.

No need for any the numpy or statistics libraries -- the average is just the sum() divided by the count.

And I think your indentation is off for when you are calculating the mean.

import csv

def calc_average_books_stock():
    
  text_file = open('book_data_file.txt', 'r')

  reader = csv.DictReader(text_file)
    
  values = []
    
  for data in reader:
        
    if int(data['STOCK']) > 0:
            
      values.append(data['COST?'])
    
  avg = sum(values) / len(values)
    
  print(f"Average Book in Stock: {round(avg, 2)}")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.