我有 5 組如下所示的值:
[[83.91649562 79.51353257]
[87.57474691 84.66544614]
[84.08067077 85.19063777]
[86.97440657 86.20994142]
[82.91694642 84.65734125]]
我的目標是將每組中的兩個值與此標準進行比較:
- 在任何串列中,如果 item1 和 item2 >= 80 AND item1 < item2,則回傳 -10
- 在任何串列中,如果 item1 和 item2 <= 20 AND item1 > item2,則回傳 10
- 否則回傳 0
這是我所做的
def myfunction(data):
data = data.iloc[:, [0, 1]].values
for x, y in enumerate(data):
if (x-y).all() >= 80 and x < y:
return -10
else:
return 0
現在我回傳 0,但是第 3 和第 5 個串列符合條件并且應該回傳 -10,所以我沒有轉到第二個 if 陳述句。我還嘗試使用以下方法設定資料:
data = data.iloc[:, [0, 1]].values.tolist()
將資料用作
[[83.91649561983937, 79.51353257164777], [87.57474691499445, 84.66544613660386], [84.08067077024245, 85.19063776835876], [86.97440656949847, 86.20994141824511], [82.91694641784167, 84.65734125252753]]
沒有運氣。我一直在使用 enumarate() 因為我在沒有收到錯誤訊息方面取得了最大的成功,但我不確定這是否是我解決這個問題所需要的。
謝謝大家!
uj5u.com熱心網友回復:
不使用任何庫,為簡化起見,您可以像這樣撰寫回圈
#Devil
lst = [[83.91649562, 79.51353257],
[87.57474691, 84.66544614],
[84.08067077, 85.19063777],
[86.97440657, 86.20994142],
[82.91694642, 84.65734125]]
fill_out = []
for i in lst:
#print(i)
item1 = i[0] ; item2 = i[1]
if item1 >= 80 and item2 >= 80 and item1 < item2:
fill_out.append(-10)
elif item1 <= 20 and item2 <= 20 and item1 > item2:
fill_out.append(10)
else:
fill_out.append(0)
print("output:",fill_out)
#output : [0, 0, -10, 0, -10]
uj5u.com熱心網友回復:
您可以嘗試以下方法:
import numpy as np
a = np.array([[83.91649561983937, 79.51353257164777],
[87.57474691499445, 84.66544613660386],
[84.08067077024245, 85.19063776835876],
[86.97440656949847, 86.20994141824511],
[82.91694641784167, 84.65734125252753]])
conds = [(np.diff(a) > 0).ravel() & np.all(a >= 80, axis=1),
(np.diff(a) < 0).ravel() & np.all(a <= 20, axis=1)]
np.select(conds, [-10, 10])
它給:
array([ 0, 0, -10, 0, -10])
uj5u.com熱心網友回復:
import pandas as pd
def myfunction(data):
where = (data[0] >= 80) & (data[1] >= 80) & (data[0] < data[1])
if len(data.loc[where]) > 0:
return -10
where = (data[0] <= 20) & (data[1] <= 20) & (data[0] > data[1])
if len(data.loc[where]) > 0:
return 10
return 0
data = pd.DataFrame([
[83.91649562, 79.51353257],
[87.57474691, 84.66544614],
[84.08067077, 85.19063777],
[86.97440657, 86.20994142],
[82.91694642, 84.65734125],
])
myfunction(data)
基于初始代碼(.iloc[]、.any())制作了這個函式,假設 OP 使用 pandas。
輸出:-10
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/489177.html
下一篇:如何遍歷嵌套字典
