多维数组中列的平方和的平方根

时间:2014-01-13 09:46:15

标签: python numpy

我正在使用numpy的多维列表

我有一个清单。

l = [[0 2 8] [0 2 7] [0 2 5] [2 4 5] [ 8 4 7]]

我需要找到平方和的平方根。

0 2 8
0 2 7
0 2 5
2 4 5
8 4 7

输出为,

l = [sqrt((square(0) + square(0) + square(0) + square(2) + square(8))  sqrt((square(2) + square(2) + square(2) + square(4) + square(4)) sqrt((square(8) + square(7) + square(5)) + square(5) + square(7))]

4 个答案:

答案 0 :(得分:9)

>>> import numpy as np
>>> a = np.array([[0, 2, 8], [0, 2, 7], [0, 2, 5], [2, 4, 5], [ 8, 4, 7]])
>>> np.sqrt(np.sum(np.square(a), axis=0))
array([  8.24621125,   6.63324958,  14.56021978])

答案 1 :(得分:3)

>>> import numpy as np
>>> np.sum(np.array(l)**2,axis=0)**.5
array([ 10.67707825,   3.46410162,  11.74734012])

答案 2 :(得分:0)

为此使用标准功能numpy.linalg.norm ...

import numpy as np
a = np.array([[0, 2, 8], [0, 2, 7], [0, 2, 5], [2, 4, 5], [ 8, 4, 7]])
np.linalg.norm(a,axis=0)

给予:

array([ 8.24621125, 6.63324958, 14.56021978])

答案 3 :(得分:-1)

您要做的是使用map / reduce

理论上可以使用嵌套for循环来完成,但可以以更实用的方式完成......

for l in matrix:
    sum all elements**2 in 
    return the squar root of the sum

一个班轮:

map(lambda x: sqrt(lambda r, z: r + z**2, x), matrix)

但为了更清楚,你可以改写它:

def SumOfSquare(lst):
    return reduce(lambda r, x: r + x**2, lst)

def ListOfRoot(lst):
    return map(lambda x: SumOfSquare(x), lst)

s = ListOfRoot(matrix) 

误读了这个问题,它没有笨拙。

相关问题