在一个元组的元组中查找最大值和最小值

4
我刚接触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)
3个回答

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)

这仍然为我提供了每行的最大值和最小值,而我需要每列的最大值和最小值(每个元组都是一行,其中内部的值构成列,就像矩阵一样)。有没有获取列的最大值和最小值的建议? - user1782742

0

我们有一个嵌套元祖:((1, 2, 3), (4, 5, 6), (7, 8, 9))。

首先,我们需要对其进行规范化。Pythonic 方法:

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

输出:[1, 2, 3, 4, 5, 6, 7, 8, 9] # 这是一个列表

将其转换为元组:tuple(flat_tuple),获取最大值:max(flat_tuple),获取最小值:min(flat_tuple)


0

这真的听起来是非内置的 numpy 模块的工作,或者取决于您的需求,也许是 pandas 模块。

在您的应用程序中添加额外的依赖不应该轻率进行,但如果您处理类似矩阵的数据量较大,则使用上述模块将使得您的代码更快且更易读。

我不建议将一个嵌套列表转换为numpy数组再转回来以获取此单一结果 - 最好使用Jannes答案的纯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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接