查找行的最大值但错误:类型' _csv.reader'的对象没有len()

时间:2017-06-30 18:23:27

标签: python csv

我试图结合使用2个功能。基本上我试图导入一个csv文件,该文件是一系列具有我需要的值的行。然后我尝试使用第二个函数" findPeaks"找到每一行的最大值。我得到的错误是我试图查看的行没有长度,但它们应该是值数组。我的错误是什么?谢谢你的帮助。

def PSD(pulseData, pulseDataTraining):

     import csv;
     import numpy as np;
     import math
     photonTraining = 0; 

     with open(pulseDataTraining,'r') as csvfile:
         photonTraining = csv.reader(csvfile);
         print(photonTraining)
         for row in photonTraining:
             findPeaks(photonTraining,-30)  

     if photonTraining == 0:
         print("this is a string")

     return np.max(photonTraining)

和第二个功能:

def findPeaks(pulse, thresh):

     import numpy as np;
     import scipy as sp;

     peakVal = 0;
     for i in range(0,len(pulse)-1):
         while(pulse[i]<thresh):
             if np.abs(pulse[i]) < np.abs(pulse[i+1]):
                 peakVal = pulse[i+1];
             else:
                 peakVal = pulse[i];


     return peakVal;

1 个答案:

答案 0 :(得分:0)

更改为以下内容:

def PSD(pulseData, pulseDataTraining):
    with open(pulseDataTraining, 'r') as csvfile:
        # Create a csv.reader from Filehandle
        csvReader = csv.reader(csvfile)

        # Create a List of Peak Values per Row from CSV
        photonTraining_peak = \
            [findPeaks(photonTraining, -30) for photonTraining in csv.reader(csvfile)]

    print('row_max:{}'.format(photonTraining_peak),)
    return np.max(photonTraining_peak)

您的findPeaks(...将会加注

TypeError: unorderable types: str() < int()

更改为

import csv
import numpy as np

def findPeaks(pulse, thresh):
    # pulse is Type List of String
    sorted_pulse = sorted(pulse, reverse=True)
    print(sorted_pulse)

    peakVal = 0
    for s in sorted_pulse:
        v = int(s)
        if v < thresh:
            if np.abs(peakVal) < np.abs(v):
                peakVal = v
        else:
            break
    return peakVal

使用Python测试:3.4.2