2016-08-05 30 views
0

我想讀取從第7行開始的數字行並將數字編譯到列表中,直到沒有更多數據,然後計算此標準偏差和%rms名單。看起來很簡單,但我不斷收到錯誤:Numpy std的計算:TypeError:無法使用彈性類型執行縮減

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

values是一個字符串數組,所以是a。使用astypea轉換爲數字類型。例如,

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

你怎麼做到這一點?你能提供一些示例代碼嗎? – alli

+0

我添加了一個例子,如果它對你有幫助,請考慮接受我的答案。 – Priyatham

+0

它確實有幫助,但我遇到了循環播放和獲取所有信息的問題 - 它似乎只能從第一行讀取,您是否知道如何解決此問題?我將編輯我的問題 – alli

相關問題