2014-02-16 72 views
0

我試圖找到數字列表的最大值列表。當找到最大值時,Python錯誤「無法使用彈性類型執行縮減」

使用Python 2.7空閒,我嘗試這樣做:

import numpy 
vectors = [[1, 2, 3], [4,5,6]] 
numpyFiles = numpy.array(vectors) 
maxRawFreq = numpyFiles.max() 

它的工作原理,並maxRawFreq = 6

我使用一個非常類似的代碼,有一個更大的列表,並使用Pydev的(Eclipse中)試過了,但我得到以下錯誤:

cannot perform reduce with flexible type

是什麼意思? (關於這個錯誤的其他SO問題給出了具體的解決方案......)。

我的代碼:

import numpy 
with open(inputFile) as f: 
    vectors = f.readlines() 

vectorLength=len(vectors[0])#number of columns (word vector length) 

numpyFiles = numpy.array(vectors) 

#both these line gave me the same error: 
#maxRawFreq = numpyFiles.max() 
maxRawFreq = numpy.max(numpyFiles) 

inputFile包含數字,像這樣:

-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
-1, 0, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 
+1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 
+2

您在字符串,而不是數字閱讀。您需要相應地投入您的輸入。 –

+0

爲什麼不使用'numpy.loadtxt'或'numpy.genfromtxt'從文件加載數據? 'file.readlines'只是返回文件中的行列表。 –

回答

1
In [81]: data=numpy.genfromtxt(inputFile, delimiter=',')[:, :-1] 

In [82]: data 
Out[82]: 
array([[-1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 
     0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], 
     [-1., 0., 0., 3., 0., 0., 1., 0., 0., 0., 0., 0., 1., 
     0., 0., 0., 0., 0., 0., 0., 0., 4., 0., 0.], 
     [ 1., 0., 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 
     0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 6.]]) 

如果你想自己反正解析它:

In [89]: with open(inputFile) as f: 
    ...:  d=[map(float, l.strip(',\n').split(',')) for l in f] 
    ...:  print d 
    ...:  
[[-1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0], [1.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6.0]] 
+0

謝謝@zhangxaochen,作品非常漂亮:-) – Cheshie

2

的問題是在這裏:

with open(inputFile) as f: 
    vectors = f.readlines() 

如果你的文件是這樣的:

a, b, c, d 
1, 1, 3, 4 
2, 3, 5, 6 
... 

你的向量應該是這樣的: ['a, b, c, d\n', '1, 1, 3, 4\n', '2, 3, 5, 6\n', ...] 然後你需要將這些字符串轉換爲數字值。

嘗試讀取CSV(或什麼是你的輸入文件)以適當的方式

+1

忘記列表中每個字符串末尾的'\ n' – zhangxaochen

+0

@zhangxaochen是的,thanx,固定的 – akaRem

+0

謝謝@akaRem,但什麼是「正確的方式」?我嘗試了'numpy.loadtxt'就像@Ashwini建議的那樣,但我不知道如何將文件中的字符串轉換爲浮點或整型... – Cheshie

相關問題