Shaheed Blackman
Shaheed Blackman

Reputation: 1

How to calculate average from text file without numpy or pandas

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

Upvotes: 0

Views: 1194

Answers (2)

Chris Curvey
Chris Curvey

Reputation: 10389

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)}")

Upvotes: 0

Daweo
Daweo

Reputation: 36520

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

Upvotes: 1

Related Questions