Numpy std计算:TypeError:无法使用灵活类型执行reduce

时间:2016-08-05 16:16:04

标签: python error-handling

我正在尝试从第7行开始读取数字行并将数字编译成列表,直到没有更多数据,然后计算此列表中的标准差和%rms。看起来很简单,但我一直收到错误:

Traceback (most recent call last):
  File "rmscalc.py", line 21, in <module>
    std = np.std(values)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/fromnumeric.py", line 2817, in std
    keepdims=keepdims)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/_methods.py", line 116, in _std
    keepdims=keepdims)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/_methods.py", line 86, in _var
    arrmean = um.add.reduce(arr, axis=axis, dtype=dtype, keepdims=True)
TypeError: cannot perform reduce with flexible type

以下是我的代码:

import numpy as np
import glob
import os

values = []
line_number = 6

road = '/Users/allisondavis/Documents/HCl'
for pbpfile in glob.glob(os.path.join(road, 'pbpfile*')): 
    lines = open(pbpfile, 'r').readlines()
    while line_number < 400 :
        if lines[line_number] == '\n':
            break
        else: 
            variables = lines[line_number].split()
            values.append(variables)
            line_number = line_number + 3
            print values

a = np.asarray(values).astype(np.float32)
std = np.std(a)
rms = std * 100
print rms

编辑:它产生一个rms(这是错误的 - 不知道为什么)但以下错误信息令人困惑:我需要计数高(选择400只是为了确保它将获得整个文件,无论多大)

 Traceback (most recent call last):
  File "rmscalc.py", line 13, in <module>
    if lines[line_number] == '\n':
IndexError: list index out of range

1 个答案:

答案 0 :(得分:1)

values是一个字符串数组,a也是。使用aastype转换为数字类型。例如,

a = np.asarray(values).astype(np.float32)
std = np.std(a)