2013-06-24 38 views
2

我想從文本文件中讀取數據並採取這種數據的意思,但我得到錯誤無法執行減少與靈活類型。我不知道爲什麼,有人可以幫忙。這是我的代碼。取平均數據讀取'錯誤不能執行減少與靈活類型'python

right=open('01phi.txt','r').readlines() 
right=str(right) 
a=np.asarray(right) 
b=np.mean(a) 
print b 

編輯:我現在用的這條線 right=np.genfromtxt('01phi.txt') 但它會產生這個錯誤Line #10 (got 3 columns instead of 7)作爲該行的數組中是不一樣大。 Using genfromtxt to import csv data with missing values in numpy這個鏈接告訴我如何忽略底線或如何填補它們,但這兩種方法都會使平均值變得更高。有沒有辦法解決這個問題?

回答

4

right是一個字符串。 np.asarray(some_string)返回一個字符串爲dtype的數組。 NumPy的np.mean函數在傳遞字符串dtype數組時引發TypeError。

In [29]: np.asarray('1 2 3') 
Out[29]: 
array('1 2 3', 
     dtype='|S5') 
In [31]: np.mean(a) 
TypeError: cannot perform reduce with flexible type 

相反,使用np.genfromtxtnp.loadtxt從文本文件加載的數組:

a = np.genfromtxt(filename, ...) 
+0

是的,這應該爲我工作,但我有一個錯誤在使用genfromtxt它說線#12(有2列,而不是5),因爲在我的文本文件底線中的數字較少。但我只想要將所有數字導入到一個數組中。我不知道如何得到arorund這 – astrochris

+0

這告訴我如何忽略底部值或填補缺失值http://stackoverflow.com/questions/3761103/using-genfromtxt-to-import-csv-data-with-missing價值在numpy但它的重要性,我不會因爲這將sque的意思。有沒有辦法解決這個問題? – astrochris

+1

有一種方法可將[自定義文件類對象傳遞給'np.genfromtxt'](http://stackoverflow.com/questions/7923214/7923287#7923287)。你可以使用類似的東西來處理短行並返回完整的行。然而,我認爲這是比你真正想在這裏使用更多的代碼。我認爲只需編寫一個預處理腳本,它將重寫舊數據文件(通過將缺失列添加零)轉換爲可由np.genfromtxt讀取的腳本。 – unutbu