Astropy:使用列名中的特定模式迭代 table 中的列
Astropy: iterating over columns in table with a certain pattern in column name
我有一个 astropy table t
这样 t.colnames
显示如下:
['a', 'b', 'c', 'err_a', 'err_b', 'err_c', 'd', 'e', 'f']
我想为 table 中的每一行确定名称中包含 '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)
有更简单的方法吗?
假设您想要所有 "err" 列的最大值,您可以这样做:
max(t[c].max() for c in t.colnames if 'err' in c)
对于每行最大值,它稍微有点棘手,因为 Astropy 表中的数据通常是面向列的。将相关列转换为 Numpy 数组并沿行轴广播 max 函数可能是最简单的;这有点棘手,因为您需要将数组从混合类型转换为单一类型(假设所有 "err" 列都是相同的数据类型,例如 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)
我有一个 astropy table t
这样 t.colnames
显示如下:
['a', 'b', 'c', 'err_a', 'err_b', 'err_c', 'd', 'e', 'f']
我想为 table 中的每一行确定名称中包含 '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)
有更简单的方法吗?
假设您想要所有 "err" 列的最大值,您可以这样做:
max(t[c].max() for c in t.colnames if 'err' in c)
对于每行最大值,它稍微有点棘手,因为 Astropy 表中的数据通常是面向列的。将相关列转换为 Numpy 数组并沿行轴广播 max 函数可能是最简单的;这有点棘手,因为您需要将数组从混合类型转换为单一类型(假设所有 "err" 列都是相同的数据类型,例如 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)