有没有办法在保持其他维度的同时制作 3D 数组的第二维度的平均值块?
Is there a way to make chunks of mean values of the 2nd dimension of a 3D array while maintaining other dimensions?
我正在尝试使用以下代码制作 3D 数组的第二维平均值块:
print(DDD_array.shape)
a = DDD_array
new_DDD = []
for i in range(len(DDD_array)):
means = list(means_of_slices(a[i],17))
new_DDD.append(means)
new_DDD = np.array(new_DDD)
print(new_DDD.shape)
final_DDD = []
for i in new_DDD:
final_DDD.append(np.repeat(i,17))
final_DDD = np.array(final_DDD)
print(final_DDD.shape)
这是我得到的输出:
(1000, 187, 9)
(1000, 11)
(1000, 187)
但是我希望输出 final_DDD 保持其原始形状 DDD_array (1000,187,9),其中只有 187 个数据点被分块到它们的均值和第三维 9值保持不变。
我means_of_slices的函数是:
from itertools import islice
def means_of_slices(iterable, slice_size):
iterator = iter(iterable)
while True:
slice = list(islice(iterator, slice_size))
if slice:
yield np.sum(slice)/len(slice)
else:
return
你能告诉我哪里出了问题以及如何解决吗?。 means 函数或我的循环有问题吗?
假设:
DDD_array.shape
是 (2,3,2)
.
DDD_array
是
[[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]]
我的理解是您预期的 final_DDD
是:
[[[ 0.5, 0.5],
[ 2.5, 2.5],
[ 4.5, 4.5]],
[[ 6.5, 6.5],
[ 8.5, 8.5],
[10.5, 10.5]]]
解法:
final_DDD = np.broadcast_to(np.mean(DDD_array, axis=-1, keepdims=True), DDD_array.shape)
注:
如果预期输出是:
[[[2., 3.],
[2., 3.],
[2., 3.]],
[[8., 9.],
[8., 9.],
[8., 9.]]]
那么你只需要传递 axis=1
而不是 axis=-1
我正在尝试使用以下代码制作 3D 数组的第二维平均值块:
print(DDD_array.shape)
a = DDD_array
new_DDD = []
for i in range(len(DDD_array)):
means = list(means_of_slices(a[i],17))
new_DDD.append(means)
new_DDD = np.array(new_DDD)
print(new_DDD.shape)
final_DDD = []
for i in new_DDD:
final_DDD.append(np.repeat(i,17))
final_DDD = np.array(final_DDD)
print(final_DDD.shape)
这是我得到的输出:
(1000, 187, 9)
(1000, 11)
(1000, 187)
但是我希望输出 final_DDD 保持其原始形状 DDD_array (1000,187,9),其中只有 187 个数据点被分块到它们的均值和第三维 9值保持不变。
我means_of_slices的函数是:
from itertools import islice
def means_of_slices(iterable, slice_size):
iterator = iter(iterable)
while True:
slice = list(islice(iterator, slice_size))
if slice:
yield np.sum(slice)/len(slice)
else:
return
你能告诉我哪里出了问题以及如何解决吗?。 means 函数或我的循环有问题吗?
假设:
DDD_array.shape
是(2,3,2)
.DDD_array
是
[[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]]
我的理解是您预期的 final_DDD
是:
[[[ 0.5, 0.5],
[ 2.5, 2.5],
[ 4.5, 4.5]],
[[ 6.5, 6.5],
[ 8.5, 8.5],
[10.5, 10.5]]]
解法:
final_DDD = np.broadcast_to(np.mean(DDD_array, axis=-1, keepdims=True), DDD_array.shape)
注: 如果预期输出是:
[[[2., 3.],
[2., 3.],
[2., 3.]],
[[8., 9.],
[8., 9.],
[8., 9.]]]
那么你只需要传递 axis=1
而不是 axis=-1