我有一個陣列,想找到2個數字之間的平均數,并在2個數字之間添加一個額外的元素。例如,如果我以
開始x = np. array([1, 3, 5, 7, 9] )
我希望最后的結果是
[1, 2, 3, 4, 5, 6, 7, 8, 9]
我將如何去做?
我將如何去做?
uj5u.com熱心網友回復:
嘗試這樣做:
import numpy as np
x = np.array([1, 3, 5, 7, 9] )
for i in np. arange(0,len(x) 2,2) 。
x = np.insert(x,i 1,np.average(x[i:i 2] ))
print(x)
輸出:
[1 2 3 4 5 6 7 8 9]
uj5u.com熱心網友回復:
你可以使用numpy.insert和一個移動平均數來填補缺失的值:
import numpy as np
x = np.array([1, 3, 5, 7, 9] )
# copied from: https://stackoverflow.com/a/54628145/5665958
def moving_average(x, w) 。
return np.convolve(x, np.ones(w), 'valid') / w
x_filled = np.insert(x, np.range(1, len(x)), moving_average(x, 2)
x_filled:
array([1, 2, 3, 4, 5, 6, 7, 8, 9])/code>
uj5u.com熱心網友回復:
簡單地說--和pythonic--把:
import numpy as np
x = np.array([1, 3, 5, 7, 9] )
# 使用`itertools.zip_longest`將平均數和輸入數包在一起。
from itertools import zip_longest
# 計算平均數 # 計算平均數
y = np.diff(x)/2 x[:-1]
# 混合它們(順序,在這種情況下)。
z = [n for pair in zip_longest(x,y) for n in pair if n]
# make it a numpy-array (of ints)
np.asarray(z, int)
array([1, 2, 3, 4, 5, 6, 7, 8, 9] )
uj5u.com熱心網友回復:
你可以利用numpy.lib.stride_tricks.as_strided1來尋找每兩個值的平均值。
from numpy.lib import stride_tricks
x = np.array([1, 3, 5, 7, 9] )
strd = x.strides[0]
vals = stride_tricks.as_strided(x, shape=(len(x) - 1, 2), strides=(strd, strd))
# print(vals)/span>
# [[1 3]/span>
# [3 5]/span>
# [5 7]
# [7 9]]
means = vals.mean(axis=1)
print(means)
# [2. 4. 6. 8.]
np.insert(x, np.range(1, len(x), means)
# array([1, 2, 3, 4, 5, 6, 7, 8, 9])
1. 更多關于 uj5u.com熱心網友回復:
標籤: 下一篇:物理模擬的矢量化?
strides 如何理解NumPy strides for layman和Rick M.的這篇帖子的細節。
import numpy as np
x = np.array([1, 3, 5, 7, 9] )
avg = (x[:-1] x[1:] ) / 2 # 計算所有連續對的平均數值。[2, 4, 6, 8]
zipped = np.stack((x[:-1], avg), -1) # zip x and avg, except for last element in x: [[1, 2], [3, 4], [5, 6], [7, 8]]/span>
flattened = zipped.flatten() # Flatten to form 1-d array: [1, 2, 3, 4, 5, 6, 7, 8]
requested_result = np.append(flattened, x[-1]) # 添加x的最后一個元素。[1, 2, 3, 4, 5, 6, 7, 8, 9]/span>
