[英]Iterating over a python array and find mean/min/max for 50 values
我有一個數組,我想把它分成子數組。 我需要知道前 50 個值的均值/最小值/最大值,然后是下一個值,依此類推。 我想在另一個矩陣中保存均值、最小值、最大值。 目前我是這樣解決的:
np.array([[a[0:50].mean(), a[0:50].min(), a[0:50].max()],
[a[51:100].mean(), a[51:100].min(), a[51:100].max()],...])
a 是矩陣。 現在這適用於非常小的陣列,但我需要它用於更大的陣列。 我正在考慮用 for 或 while 循環解決它,但我嘗試的一切都失敗了。
使用array_split :
a = np.array(range(200))
b = np.array([[x.mean(), x.min(), x.max()]
for x in np.array_split(a, a.shape[0]/50)])
>>> b
array([[ 24.5, 0. , 49. ],
[ 74.5, 50. , 99. ],
[124.5, 100. , 149. ],
[174.5, 150. , 199. ]])
這里不是完整的解決方案,但我的意見應該會有所幫助。
基本上,獲取數組的長度,分割點,然后使用 np.split 將它們分開。
# get the length of the array, divide by 50.
# converting to int so there's no decimals
fifties = int(len(np.array) / 50)
# convert this to an array to work through
fifties = np.arange(fifties)
# get the split points
# this could be combined into the command above
for i in fifties:
fifties[i] = fifties[i] * 50
# split the array per 50 into new arrays / dimensions on the array
newarray = np.split(np.array,fifties)
# iterate through each new array
# len(newarray) gives the number of arrays, start at 1, not 0 though
for i in range(1,len(newarray):
print('Group '+str(i)+':')
print(newarray[i].mean())
print(newarray[i].min())
print(newarray[i].max())
輸出:
第 1 組:
24.5
49
0
第 2 組:
74.5
99
50
第 3 組:
127.0
154
100
我希望這有幫助!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.