[英]Comparing symbolic mathematical expressions with Python using Sympy
[英]Comparing array elements using mathematical symbols in Python
我有一個數組A
。 我正在比較A[i+1]=A[i]
但當前輸出以 0 和 1 表示。 相反,我希望它以< or = or >
的形式給出。 我提出了預期的輸出。
import numpy as np
A=np.array([np.array([[0.01609 , 0.01728839, 0.01635707],
[0.01696908, 0.01661592, 0.0163007 ],
[0.01609 , 0.01642818, 0.01950431]]),
np.array([[[0.01609 , 0.01728839, 0.01635707],
[0.01696908, 0.01661592, 0.0163007 ],
[0.01609 , 0.01642818, 0.01950431]]]),
np.array([[[0.01609 , 0.017286 , 0.01635698],
[0.01698125, 0.01659415, 0.01630078],
[0.01627952, 0.01639007, 0.01951677]]])], dtype=object)
for i in range(0,len(A)-1):
B=(A[i+1]==A[i]).astype(int)
print([B])
當前輸出為
[array([[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]])]
[array([[[1, 0, 0],
[0, 0, 0],
[0, 0, 0]]])]
預期的輸出是
[array([[=, =, =],
[=, =, =],
[=, =, =]]])]
[array([[[=, <, <],
[>, <, >],
[>, <, >]]])]
您可以使用numpy 廣播和np.select
避免 for 循環:
mapping = {
"<": A[1:] < A[:-1],
"=": A[1:] == A[:-1],
">": A[1:] > A[:-1],
}
choicelist, condlist = zip(*mapping.items())
result = np.select(condlist, choicelist)
# equivalent to
# result = np.select(mapping.values(), mapping.keys())
>>> result
array([[['=', '=', '='],
['=', '=', '='],
['=', '=', '=']],
[['=', '<', '<'],
['>', '<', '>'],
['>', '<', '>']]], dtype='<U3')
你可以使用np.select
for i in range(len(A)-1):
B = np.select([A[i+1]==A[i],A[i+1]>A[i],A[i+1]<A[i]], ["=",">","<"])
print([B])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.