Averaging a list in Python, "Type Error: Cannot perform reduce with flexible type"

时间:2015-06-25 18:36:15

标签: python numpy

The code below is supposed to do as follows:

  1. Fill an empty list with a specific column of numbers from a csv file.

  2. The average of the list values is then calculated and the resulting value is plotted.

Problems: I keep getting the error "TypeError: cannot perform reduce with flexible type". All I do know is that it has to do something with condensing down a list. But I'm not sure beyond that. Any help is appreciated.

import csv 
import matplotlib.pyplot as plt 
import numpy as np 

channelData = []

channelSel = int(input("Select a channel to view "))

with open('PrivateData.csv', newline='') as f: 
    reader = csv.reader(f)
    for row in reader:
        channelData.append(row[channelSel])

averagemV = np.mean(channelData)

plt.plot(averagemV) 
plt.ylabel("Average mV")
plt.xlabel("Channel " + str(channelSel))
plt.show()

2 个答案:

答案 0 :(得分:3)

with open('PrivateData.csv', newline='') as f: reader = csv.reader(f) for row in reader: channelData.append(row[channelSel]) I suspect that this is adding strings that look like floats to channelData, rather than actual floats. Try explicitly converting. with open('PrivateData.csv', newline='') as f: reader = csv.reader(f) for row in reader: channelData.append(float(row[channelSel]))

答案 1 :(得分:0)

作为替代方案,numpy.genfromtxt允许您将整个文件读入二维数组,并通过一些更改实现相同的结果。

data.txt

1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
with open('data.txt') as f:
    a = np.genfromtxt(f, delimiter=',')

>>> a
array([[  1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.],
       [  9.,  10.,  11.,  12.],
       [ 13.,  14.,  15.,  16.]])
>>> channelSel = 1
>>> mean = a.mean(axis = 0)
>>> mean
array([  7.,   8.,   9.,  10.])
>>> averagemV = mean[channelSel]
>>> averagemV
8.0
>>>