我是python的新手,我想从文本文件中获得多个平均值。例如:
56,1,2,120,236,0,0,178,0,0.8,1,0,3,0
就像我只想获得像1,4,5这样的某些列的平均值。
import pandas as pd
df = pd.read_csv('HDPV.txt', "rb")
columns = f.readline().strip().split(" ")
numRows = 0
sums = [0] * len(columns)
for line in f:
if not line.strip():
continue
values = line.split(" ")
for i in xrange(len(values)):
sums[i] += int(values[i])
numRows += 1
for index, summedRowValue in enumerate(sums):
print ('average age:'columns[0],summedRowValue / numRows)
print ('average chol:'columns[3],summedRowValue / numRows)
print ('bp:'columns[4],summedRowValue / numRows)
答案 0 :(得分:1)
我不使用pandas,但使用python list comprehension可以很容易地解决这个问题:
import csv
with open('text.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
rows = [[value.strip() for value in row] for row in reader]
average_age_list = [float(row[0]) for row in rows]
print ('average age: ' + str(sum(average_age_list) / float(len(average_age_list))))
average_chol_list = [float(row[3]) for row in rows]
print ('average chol: ' + str(sum(average_chol_list) / float(len(average_chol_list))))
bp_list = [float(row[4]) for row in rows]
print ('average age: ' + str(sum(bp_list) / float(len(bp_list))))
请参阅https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions