2012-10-29 65 views
2

我是新來的Python的元組的最大值和最小值,並具有發現的最低和最高值的元組的元組的一些問題。我需要他們正常化我的數據。所以,基本上,我有一個列表是13行數字,每個代表一些東西。每個數字在列表中都有一列,我需要每列都有maxmin。我嘗試索引/迭代,但不斷得到一個錯誤發現在元組

max_j = max(j) 

TypeError: 'float' object is not iterable 

任何幫助,將不勝感激!

的代碼(假設data_set_tup是元組的元組,例如,((1,3,4,5,6,7,...),(5,6,7,3,6,73,2 ...)...(3,4,5,6,3,2,2 ...))我也想使用標準化的值創建一個新列表

normal_list = [] 

for i in data_set_tup: 

    for j in i[1:]: # first column doesn't need to be normalised 
     max_j = max(j) 
     min_j = min(j) 
     normal_j = (j-min_j)/(max_j-min_j) 
     normal_list.append(normal_j) 
    normal_tup = tuple(normal_list) 

回答

4

您可以將行與zip(*...)列,反之亦然。(在Python 3使用list(zip(*...))

cols = zip(*data_set_tup) 
normal_cols = [cols[0]] # first column doesn't need to be normalised 
for j in cols[1:]: 
    max_j = max(j) 
    min_j = min(j) 
    normal_cols.append(tuple((k-min_j)/(max_j-min_j) for k in j) 

normal_list = zip(*normal_cols) 
+0

這仍然給我每行的最大值和最小值,而我需要每列的最大值和最小值(每個元組是行,其中的值構成列,就像一個矩陣)。有關獲取列的最大值和最小值的任何建議? – user1782742

+0

@ user1782742已修改。 –

0

這聽起來真的像非內置numpy模塊,或者也許是pandas模塊作業,取決於喲你的需求。

對應用程序添加額外的依賴關係不應輕易做,但如果您在類矩陣數據上做了大量工作,那麼如果您使用上述模塊之一,則代碼可能更快且更易讀整個應用程序。

我不推薦列表的列表轉換爲numpy的陣列,然後再返回剛剛得到這個單一的結果 - 這是更好地使用雅尼答案的純Python方法。另外,看到你是一名Python初學者,現在numpy可能會過度殺傷。但我認爲你的問題值得回答指出,這個的一個選項。

這裏是如何做到這一點的工作numpy的一步一步的控制檯圖解:

>>> import numpy as np 
>>> a = np.array([[1,3,4,5,6],[5,6,7,3,6],[3,4,5,6,3]], dtype=float) 
>>> a 
array([[ 1., 3., 4., 5., 6.], 
     [ 5., 6., 7., 3., 6.], 
     [ 3., 4., 5., 6., 3.]]) 
>>> min = np.min(a, axis=0) 
>>> min 
array([1, 3, 4, 3, 3]) 
>>> max = np.max(a, axis=0) 
>>> max 
array([5, 6, 7, 6, 6]) 
>>> normalized = (a - min)/(max - min) 
>>> normalized 
array([[ 0.  , 0.  , 0.  , 0.66666667, 1.  ], 
     [ 1.  , 1.  , 1.  , 0.  , 1.  ], 
     [ 0.5  , 0.33333333, 0.33333333, 1.  , 0.  ]]) 
在實際代碼

所以:

import numpy as np 

def normalize_by_column(a): 
    min = np.min(a, axis=0) 
    max = np.max(a, axis=0) 
    return (a - min)/(max - min) 
0

我們有nested_tuple = ((1, 2, 3), (4, 5, 6), (7, 8, 9))。 首先,我們需要對其進行標準化。 Python的方式:

flat_tuple = [x for row in nested_tuple for x in row] 

輸出:[1,2,3,4,5,6,7,8,9] # it's a list

它移動到元組:tuple(flat_tuple),得到最大值:max(flat_tuple),得到最小值:min(flat_tuple)