Skip to main content
 首页 » 编程设计

python之分配一个新列,该列动态地在 numpy 数组的索引上使用指数函数

2025年05月04日13mq0036

假设我有一个具有以下性质的数组:

x = arange(30).reshape((10,3)) 
x 
Out[52]:  
array([[ 0,  1,  2], 
       [ 3,  4,  5], 
       [ 6,  7,  8], 
       [ 9, 10, 11], 
       [12, 13, 14], 
       [15, 16, 17], 
       [18, 19, 20], 
       [21, 22, 23], 
       [24, 25, 26], 
       [27, 28, 29]]) 

如何向每一行添加第四列,使该列是索引号的指数函数,并以如下形式结束:

array([[ 0,  1,  2,   2.718281828], 
   [ 3,  4,  5,   7.389056099], , 
   [ 6,  7,  8,   20.08553692], 
   [ 9, 10, 11,   54.59815003 ], 
   [12, 13, 14,   148.4131591], 
   [15, 16, 17,  403.4287935], 
   [18, 19, 20,  1096.633158 ], 
   [21, 22, 23,  2980.957987], 
   [24, 25, 26,  8103.083928], 
   [27, 28, 29,  22026.46579]]) 

请您参考如下方法:

计算指数很容易:

ex = np.exp(np.arange(x.shape[0]) + 1) 

你想用它做什么是一个完全不同的故事。 Numpy 不允许异构数组,不像说 Pandas 。因此,使用简单的答案,您的结果将是 float64(x 很可能是 int64 或 int32):

x = np.concatenate((x, ex[:, None]), axis=1) 

另一种方法是使用 structured arrays ,这将使您保留输入类型:

d = [('', x.dtype)] * x.shape[1] + [('', ex.dtype)] 
out = np.empty(ex.shape, dtype=d) 

批量分配有点棘手,但可以通过从原始 ndarray 获得的 View 来完成构造函数:

view = np.ndarray(buffer=out, dtype=x.dtype, shape=x.shape, strides=(out.dtype.itemsize, x.dtype.itemsize)) 
view[...] = x 
 
np.ndarray(buffer=out, dtype=ex.dtype, shape=ex.shape, strides=(out.dtype.itemsize,), offset=x.strides[0])[:] = ex 

一个更简单的方法是使用 recarray , 作为 @PaulPanzer suggests :

out = np.core.records.fromarrays([*x.T, ex])