numpy,标量乘法数组

时间:2018-11-26 16:22:05

标签: python python-2.7 numpy numpy-ufunc

是否可以使用ufuncs https://docs.scipy.org/doc/numpy/reference/ufuncs.html
为了将函数映射到数组(1D和/或2D)和标量
如果不是,我将如何实现这一目标?
例如:

# Use a single Get-CimInstance call to target all computers and
# quietly collect errors for later analysis.
$computerNames = (Get-ADComputer -Filter 'Name -like "L*"' -Properties *).Name
Get-CimInstance -ErrorAction SilentlyContinue -ErrorVariable errs `
                -ComputerName $computerNames -Class Win32_ComputerSystem |             #`
  ForEach-Object {
    "Computer: $($_.Name) Username: $(($_.UserName -split '\\')[-1])" 
  }

# Analyze the errors that occurred, if any.
$errs | ForEach-Object {
  if ($_.Exception -is [Microsoft.Management.Infrastructure.CimException] -and $_.CategoryInfo.Category -eq 'ConnectionError') {
    Write-Warning "Computer is unavailable: $($_.OriginInfo.PSComputerName)"
  } else { # unexpected error, pass it through
    Write-Error $_
  }
}

预期结果:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <symbol viewBox="0 0 28.3 28.3" id="square">
      <path d="M.3 30.7h27L13.8 3.8zM126.3-51.7c-8.8 0-16 7.2-16 16s7.2 16 16 16 16-7.2 16-16-7.2-16-16-16z" />
      <path d="M0 28.3h28.3L14.2 0 0 28.3zm5.3-3.2l8.9-17.7L23 25.1H5.3z" />
    </symbol>
    <symbol viewBox="0 0 28.3 28.3" id="circle">
      <circle cx="14.2" cy="14.2" r="14.2" />
    </symbol>
  </defs>
</svg>

如果与问题相关,我正在使用python 2.7。

2 个答案:

答案 0 :(得分:4)

您可以将numpy数组乘以标量,这样就可以了。

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

这也是非常快速有效的操作。以您的示例为例:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

答案 1 :(得分:1)

使用.multiply() ufunc乘法

class Builder:
    def __init__(self,version='0.0.1'):
        self.version = version

    def build(self):
        return MyObject(self.version)

    @staticmethod
    def factory(version):
        return Builder(version).build()

versioned_obj = Builder.factory('0.0.1')