0
votes

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
What is the type of each element in channelData? - Kevin
@Kevin integer. The 5th line of code you can see that it's a user input read as an integer. - DeeWBee
Looks to me like the error is coming from the numpy package, you may want to add that tag. - A. L. Flanagan
But you're not appending channelSel to channelData, you're appending row[channelSel], which might not necessarily have the same type as channelSel. - Kevin
@Kevin the values I'm working with are technically float values. row[channelSel] really means take the [channelSel]th value in each row of the csv file - DeeWBee

2 Answers

3
votes
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]))
0
votes

As an alternative, numpy.genfromtxt allows you to read the entire file into a 2d array and with a couple of changes achieve the same result.

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
>>>