1

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

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]
4

1 回答 1

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]

数据在两个轴上对齐,但我不确定你想要从你的问题中得到哪个。

于 2013-09-12T18:43:27.680 回答