温馨提示:本文翻译自stackoverflow.com,查看原文请点击:max - Astropy: iterating over columns in table with a certain pattern in column name
max astropy

max - 熵:使用列名中的特定模式遍历表中的列

发布于 2020-03-28 23:42:52

我有一个令人讨厌的表tt.colnames显示如下:

['a', 'b', 'c', 'err_a', 'err_b', 'err_c', 'd', 'e', 'f']

我想为表中的每一行确定'err'名称中具有的列的最大值

我可以做类似的事情

for line in t:
    max = 0
    for col in t.colnames:
        if col[:3] == 'err':
            if line[col] > max:
                max = line[col]
    print(max)

有没有更简单的方法可以做到这一点?

查看更多

查看更多

提问者
usernumber
被浏览
15
Iguananaut 2020-01-31 18:54

假设您想要所有“ err”列中的最大值,则可以执行以下操作:

max(t[c].max() for c in t.colnames if 'err' in c)

对于最大每行来说,这有点棘手,因为Astropy表中的数据通常是面向列的。将相关列转换为Numpy数组并沿行轴广播max函数可能是最简单的。这有点棘手,因为您需要将数组从混合类型转换为单一类型(假设所有“ err”列都是相同的dtype,例如float64):

err_cols = [c for c in t.colnames if 'err' in c]
t.as_array(names=err_cols).view(dtype=float).reshape((len(t), len(err_cols))).max(axis=1)