【发布时间】:2016-03-23 20:27:42
【问题描述】:
我是 python 新手,我想从文本文件中获取多个平均值。例如:
- 63, 1, 1, 145, 233, 1, 2, 150, 0, 2.3, 3, 0, 6, 0
- 67、1、4、160、286、0、2、108、1、1.5、2、3、3、2
- 67、1、4、120、229、0、2、129、1、2.6、2、2、7、1
- 37, 1, 3, 130, 250, 0, 0, 187, 0, 3.5, 3, 0, 3, 0
- 41, 0, 2, 130, 204, 0, 2, 172, 0, 1.4, 1, 0, 3, 0
-
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)
【问题讨论】:
-
给定示例的预期输出是什么?
-
类似:平均年龄:55 /n 平均 chol:xxx /n bp:xxx 我不确定我是否使用了正确的评论。
-
'f' 似乎是未定义的。
-
您正在使用 Pandas 读取文件。为什么不简单地使用
df.mean()来获取每列的平均值? -
标签: python python-3.x pandas