[英]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.