从生成的数组列表中对索引求和

时间:2013-09-12 18:34:37

标签: python-2.7 numpy

您好我有从下面定义的函数生成的数组列表。我想知道是否有办法在列表中的每个数组中总结相同的索引,只给我一个数组?

import numpy as np       
Tsp = np.linspace(3500, 40000, 3)
wcm = np.linspace(100, 10000, 5)    
def blackbody(T, wcm):
    k = 1.38*10**-16.0 #ergs/k                                                  
    h = 6.625*10**-27.0 #erg/s                                                  
    c = 3*10.0**10.0 #cm/s                                                      
    bbtop = (2.0*h*c**2.0)
    bbbot = (wcm**5.0)*(np.exp((h*c)/(wcm*k*T)) - 1)
    bbs = bbtop/bbbot
    return bbs

outflux = [blackbody(T_i, wcm) for T_i in Tsp]

1 个答案:

答案 0 :(得分:2)

将定义更改为:

def blackbody(T, wcm):
    k = 1.38*10**-16.0 #ergs/k
    h = 6.625*10**-27.0 #erg/s
    c = 3*10.0**10.0 #cm/s
    bbtop = (2.0*h*c**2.0)

    T = np.atleast_1d(T)       #So you can pass a single number if desired.
    bbbot = (wcm**5.0)*(np.exp((h*c)/(wcm*k*T[:,None])) - 1) #Changed T to T[:,None]
    bbs = bbtop/bbbot
    return bbs

现在您可以将其命名为:

blackbody(Tsp, wcm)

仔细检查它们是否相等:

looped = np.array([blackbody(T_i, wcm) for T_i in Tsp])
broadcast = blackbody(Tsp, wcm)

print np.allclose(looped,broadcast)
True

既然你有一个阵列,你可以使用np.sum

在所需的轴上求和
data = blackbody(Tsp, wcm)
data
[[  2.89799404e-10   6.59157826e-16   4.45587348e-17   9.03800033e-18
    2.89799993e-18]
 [  1.80089940e-09   4.09619532e-15   2.76900716e-16   5.61647169e-17
    1.80089999e-17]
 [  3.31199940e-09   7.53323285e-15   5.09242710e-16   1.03291433e-16
    3.31200005e-17]]

np.sum(data,axis=1)
[  2.89800119e-10   1.80090385e-09   3.31200758e-09]

np.sum(data,axis=0)
[  5.40269821e-09   1.22885860e-14   8.30702161e-16   1.68494151e-16
   5.40270004e-17]

数据在两个轴上都是对齐的,但我不确定你想从问题中找到什么。