如何在NumPy数组中的特定列上乘标量?

问题描述 投票:23回答:3

我需要对水文地质野外工作的大型数据集进行一些分析。我正在使用NumPy。我想知道如何:

  1. 例如我的数组的第二列,以数字表示(例如5.2)。然后

  2. 计算该列中数字的累加和。

正如我提到的,我只想处理特定的列,而不要处理整个数组。

python arrays numpy multidimensional-array
3个回答
30
投票
 you can do this in two simple steps using NumPy:

>>> # multiply column 2 of the 2D array, A, by 5.2
>>> A[:,1] *= 5.2

>>> # assuming by 'cumulative sum' you meant the 'reduced' sum:
>>> A[:,1].sum()

>>> # if in fact you want the cumulative sum (ie, returns a new column)
>>> # then do this for the second step instead:
>>> NP.cumsum(A[:,1])

带有一些模拟数据:

>>> A = NP.random.rand(8, 5)
>>> A
  array([[ 0.893,  0.824,  0.438,  0.284,  0.892],
         [ 0.534,  0.11 ,  0.409,  0.555,  0.96 ],
         [ 0.671,  0.817,  0.636,  0.522,  0.867],
         [ 0.752,  0.688,  0.142,  0.793,  0.716],
         [ 0.276,  0.818,  0.904,  0.767,  0.443],
         [ 0.57 ,  0.159,  0.144,  0.439,  0.747],
         [ 0.705,  0.793,  0.575,  0.507,  0.956],
         [ 0.322,  0.713,  0.963,  0.037,  0.509]])

>>> A[:,1] *= 5.2

>>> A
  array([[ 0.893,  4.287,  0.438,  0.284,  0.892],
         [ 0.534,  0.571,  0.409,  0.555,  0.96 ],
         [ 0.671,  4.25 ,  0.636,  0.522,  0.867],
         [ 0.752,  3.576,  0.142,  0.793,  0.716],
         [ 0.276,  4.255,  0.904,  0.767,  0.443],
         [ 0.57 ,  0.827,  0.144,  0.439,  0.747],
         [ 0.705,  4.122,  0.575,  0.507,  0.956],
         [ 0.322,  3.71 ,  0.963,  0.037,  0.509]])

>>> A[:,1].sum()
  25.596156138451427

仅需要一些简单的规则即可在NumPy中进行元素选择(索引):

  • NumPy,就像Python,也是基于0的,因此例如下面的“ 1”是指第二列

  • 逗号将括号内的尺寸分开,因此[行,列],例如A [2,3]表示第三行第四列的​​项目(“单元格”)>]

  • 冒号表示该维度上元素的all

  • ,例如A [:,1]创建A的列2的视图; A [3 ,:]指向第四行

6
投票

确定:


0
投票

将常数与特定的列或行相乘:

© www.soinside.com 2019 - 2024. All rights reserved.