简体   繁体   English

如何在没有 numpy 或 pandas 的情况下从文本文件计算平均值

[英]How to calculate average from text file without numpy or pandas

Here is the code I used to calculate average with numpy and pandas这是我用来计算 numpy 和 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我想知道在没有 numpy 和 pandas 的情况下是否有办法做到这一点,并且只能使用 python 的标准库来做到这一点

do it with python's standard library You might use .mean from statistics built-in module to calculate average, for example:用 python 的标准库来做你可以使用statistics内置模块中的.mean来计算平均值,例如:

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

output: output:

20

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.我不确定df的来源,但如果您的文件是某种 CSV 格式,您可以将 pandas 替换为 csv。

No need for any the numpy or statistics libraries -- the average is just the sum() divided by the count.不需要任何 numpy 或统计库——平均值只是sum()除以计数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用 pandas 或 numpy 等库的情况下计算二维列表中测试分数的百分比和平均值 - How to calculate percentage and average of test scores in a 2D list without using libraries like pandas or numpy 如何使用MRJob从文本文件计算平均值 - How to calculate the average number from a text file with MRJob 在不使用 Numpy 和 Pandas 的情况下从列表列表中计算平均值? - Calculating average from a list of lists without using Numpy and Pandas? 如何计算numpy的多个平均值? - How to calculate multiple average in numpy? 如何使用numpy按季度分组并计算数组的平均值? - How to group by quarter and calculate average from an array using numpy? Pandas:如何计算分组的平均值 - Pandas: How to calculate the average of a groupby 如何从文本文件中读取值并计算值重复多少次,然后求平均值? - How can I read in values from a text file and calculate how many times a value repeats and then find the average? python pandas dataframe 月销售数据的平均值如何计算 - How to calculate average of monthly sales data from python pandas dataframe 如何从文本文件计算python 2.7中的平均单词和句子长度 - How to calculate average word & Sentence length in python 2.7 from a text file 如何计算 numpy 中数组中最近邻居的平均值 - How to calculate average of closest neighbours in an array in numpy
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM