选择.csv中的列并对其进行操作


问题内容

我有38列和1500+行的csv,其中包含浮点数和字符串。我想从该集合中获取3列(x,y,z)浮动数据以找到的平均值f=(x+y)/z。经过研究,我成功地将这些列分离为numpy数组并执行了f=(x+y)/z。现在,当我尝试求和f时,不会将数组相加。我打印f并且看到1500个正确值的项目,但不是这些总和的值。

  reader=csv.reader(open('myfile.csv' ,"rb"),delimiter=',')
  reader.next()
  reader.next()
  x=list(reader)
  data=numpy.array(x)
  rows=data.shape[0]
  for i in range (0,rows):
      x=numpy.array(data[i,18]).astype('float')
      y=numpy.array(data[i,19]).astype('float')
      z=numpy.array(data[i,6]).astype('float')
      f=numpy.array((x+y)/z)
      average=numpy.sum(f)/rows
      print average

问题答案:

如果data已经是数组,则不需要for循环:

x = data[:, 18].astype(float)
y = data[:, 19].astype(float)
z = data[:, 6].astype(float)
f = (x+y) / z
average = np.average(f)

使用np.loadtxt以下命令读取文件可能会更好:

data = np.loadtxt('myfile.csv', dtype=float, delimiter=',' skiprows=2,
                  usecols=(6, 18, 19))

或获得xyz直接:

x, y, z = np.loadtxt('myfile.csv', dtype=float, delimiter=',' skiprows=2,
                     usecols=(6, 18, 19), unpack=True)