簡體   English   中英

將numpy數組解析轉換為常規python語法

[英]Convert numpy arrays comprehensions to regular python syntax

我不確定是否為標題使用了正確的術語,因為我從未使用過python numpy模塊,但是我從特定代碼中看到兩行,這使我感到困惑:這兩個:

IAM[theta == 0]=1
IAM[abs(theta) > 90 | (IAM < 0)]=0

來源: https : //github.com/Sandia-Labs/PVLIB_Python/blob/master/pvlib/pvl_physicaliam.py#L109-111

我想知道是否可以將它們翻譯成常規的Python代碼? 上兩個實際上是否表示:

theta = 10  # for example

newIAM = []
for item in IAM:
    if item == 0:
       newIAM.append(1)
    else:
       newIAM.append(item)

和:

newIAM = []
for item in IAM:
    if (abs(theta) > 90) and (item < 0)
       newIAM.append(0)
    else:
       newIAM.append(item)

我正在使用python 2.7。 感謝您的幫助。

IAM是向量,theta可以是向量或標量。

IAM[theta == 0]=1

將IAM的每個值設置為1,其中相應的theta為零。

IAM[abs(theta) > 90 | (IAM < 0)]=0

(應該)將IAM的每個值設置為0,其中相應的絕對theta值大於90或IAM小於零。

import numpy as np
IAM = np.array( [3, 2, 3, 4, 5] )
# theta can be shorter than IAM
theta = np.array( [0, 1, 0, 1])
IAM[theta==0] = 1
# when theta is a scalar only the fist value will be tested and perhaps changed
# theta[0] is 0 => set IAM[0] to 0
# theta[1] is not 0 => do not change IAM[1]
# ...
#IAM = [1 2 1 4 5]

等效的純python解決方案:

from itertools import izip_longest
IAM = [3, 2, 3, 4, 5]
theta = [0, 1, 0, 1]
newIAM = []

try:
    for iam, t in izip_longest(IAM, theta):
        if t == 0:
            newIAM.append(1)
        else:
            newIAM.append(iam)
except TypeError:
    newIAM.extend(IAM)
    if theta == 0:
        neaIAM[0]=1

第二行不能按預期工作。

import numpy as np
IAM = np.array( [-1, 2, 3, -5, 1])
theta = np.array( [1, 2, -91, 3, 4])
IAM[(abs(theta) > 90) | (IAM < 0)]=0
# IAM is [0, 2, 0, 0, 1]

如果沒有括號,則abs(theta)> 90,它將檢查abs(theta)是否大於(90 |(IAM <0))。 90 | (IAM <0)如果IAM> = 0則求值為90,如果IAM <0則求91。

似乎是您發布的代碼中的錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM