gpt4 book ai didi

arrays - 如何获取嵌套numpy数组的各列的所有平均值?

转载 作者:行者123 更新时间:2023-12-03 08:11:24 25 4
gpt4 key购买 nike

我在为dim-2 numpy数组的每一列执行按列操作时遇到麻烦。尽管我的设置不同,但是我试图使我的情况适应this answer。我的实际数据集很大,并且涉及多个重采样,因此下面示例的语法。如果代码和说明看起来太长,请考虑跳至标题相关

可跳过(仅在此处复制下面的zs)

考虑一个(x_n, y_n)数据集,其中n = 0, 1, or 2

def get_xy(num, size=10):
## (x1, y1), (x2, y2), (x3, y3) where xi, yi are both arrays
if num == 0:
x = np.linspace(7, size+6, size)
y = np.linspace(3, size+2, size)
elif num == 1:
x = np.linspace(5, size+4, size)
y = np.linspace(2, size+1, size)
elif num == 2:
x = np.linspace(4, size+3, size)
y = np.linspace(1, size, size)
return x, y

假设给定数组 z_nx_n,我们可以计算一些度量 y_n
def get_single_z(x, y, constant=2):
deltas = [x[i] - y[i] for i in range(len(x)) if len(x) == len(y)]
return constant * np.array(deltas)

无需单独计算每个 z_n,我们可以一次计算所有 z_n
def get_all_z(constant=2):
zs = []
for num in range(3): ## 0, 1, 2
xs, ys = get_xy(num)
zs.append(get_single_z(xs, ys, constant))
zs = np.array(zs)
return zs

相关:
zs = get_all_z()
print(zs)
>> [[ 8. 8. 8. 8. 8. 8. 8. 8. 8. 8.]
[ 6. 6. 6. 6. 6. 6. 6. 6. 6. 6.]
[ 6. 6. 6. 6. 6. 6. 6. 6. 6. 6.]]

出于我的目的,我想创建一个新的列表或数组 vs,其每个索引处的值等于 zs相应列中的值的平均值。对于这种情况, vs的每个元素都是相同的(因为每个操作都是[8,6,6]的平均值)。但是,如果第一个子数组的第一个元素是10而不是8,那么 vs的第一个元素将是[10,6,6]的平均值。

尝试失败:
def get_avg_per_col(z):
## column ?= axis number
return [np.mean(z, axis=i) for i in range(len(zs[0]))]

print(get_avg_per_col(zs))
Traceback (most recent call last):...
...line 50, in _count_reduce_items ## of numpy code, not my code
items *= arr.shape[ax]
IndexError: tuple index out of range

最佳答案

您可以在转置的np.mean上使用zs来获取列明智的平均值。

In [49]: import numpy as np

In [53]: zs = np.array([[ 8., 8., 8., 8., 8., 8., 8., 8., 8., 8.],
...: [ 6., 6., 6., 6., 6., 6., 6., 6., 6., 6.],
...: [ 6., 6., 6., 6., 6., 6., 6., 6., 6., 6.]])

In [54]: np.mean(zs.T, axis=1)
Out[54]:
array([ 6.66666667, 6.66666667, 6.66666667, 6.66666667, 6.66666667,
6.66666667, 6.66666667, 6.66666667, 6.66666667, 6.66666667])

关于arrays - 如何获取嵌套numpy数组的各列的所有平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44961609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com