我有這個數字串列:{199, 200, 208, 210, 200, 207, 240}。
我想確定串列中的數字是如何增加或減少的。例如,在 199 之后,我有 200,差異為 1。但在 200 之后,我有 208,差異為 8。如何確定 Python 中整個串列的增加/減少量度?
其次,我想計算數字增加了多少次。由于串列由增加和減少的數字組成,我只想計算它增加了多少次。
謝謝你。
uj5u.com熱心網友回復:
您可以使用 zip() 將元素與其后繼元素配對并在串列推導式中處理它們:
numbers = [199, 200, 208, 210, 200, 207, 240]
increments = [b-a for a,b in zip(numbers,numbers[1:]) if b>a]
decrements = [b-a for a,b in zip(numbers,numbers[1:]) if a>b]
print(increments) # [1, 8, 2, 7, 33]
print(decrements) # [-10]
print(len(increments)) # 5
您還可以直接獲取遞增對的數量(無需構建遞增串列):
sum(b>a for a,b in zip(numbers,numbers[1:])) # 5
uj5u.com熱心網友回復:
解決您的問題 #1,您可以計算 Spearmans 相關性與 x 值的增加。它的值在 [-1, 1] 范圍內,如果值為正,則 y 會隨著 x 的增加而增加,如果值為負,則 y 會隨著 x 的增加而減少,如果值為零,則沒有相關性。如果值很高,接近 1 或 -1,則強烈表明這兩個資料高度相關。因此,即使您不繪制資料,您也可以通過了解 Spearmans 值來判斷趨勢是正相關還是負相關或沒有相關性。
代碼
from scipy.stats import spearmanr
import matplotlib.pyplot as plt
y = [199, 200, 208, 210, 200, 207, 240]
x = range(len(y))
# calculate spearman's correlation
corr, _ = spearmanr(x, y)
print('Spearmans correlation: %.3f' % corr)
plt.plot(x, y, '--*')
plt.savefig('corr.png')
plt.show()
輸出
Spearmans correlation: 0.667

參考
- https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html
- https://en.wikipedia.org/wiki/Spearman's_rank_correlation_coefficient
uj5u.com熱心網友回復:
l = [199,200,208,210,200,207,240]
diff = [l[i 1] - l[i] for i in range(len(l) - 1)]
# count the number of increasing changes
num_inc = sum([l[i 1] > l[i] for i in range(len(l) - 1)]) # 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371037.html
