使用 vectorise 时在 python numpy.mean 函数中遇到奇怪的问题

Encountering strange issue in python numpy.mean function when using vectorise

我正在编写一个函数并将嵌套列表传递给它。目标是找到每个嵌套列表的平均值。例如。如果下面是输入

[[1914.05004882812], [1930.65002441406, 1934.5]]

我希望输出如下所示,每个列表的平均值。

[1914.05004883 1932.57501221]

这对某些值有效,但对于某些值,我得到的是嵌套列表。下面是函数和输出。你能告诉我我在这里做错了什么吗?我正在学习 python,如果我使用的术语不正确,请原谅。我正在使用 google colab 对此进行测试。

def groupmeancalc(groups):
  print('type of group is ' + str(type(groups)))
  print(groups)
  print('size of group is ' + str(len(groups)))
  if len(groups)==1:
    nparrr=np.array(groups)
    nparr=np.mean(nparrr)
    print('Below are the values')
    print(nparr)
  else:
    nparrr=np.array(groups)
    nparr=np.vectorize(np.mean)(nparrr)
    print('Below are the values')
    print(nparr)

以下是预期的输出。

type of group is <class 'list'>
[[1918.80004882812], [1938.69995117188, 1940.05004882812]]
size of group is 2
Below are the values
[1918.80004883 1939.375     ]


type of group is <class 'list'>
[[5510.2001953125, 5519.9501953125], [5545.10009765625]]
size of group is 2
Below are the values
[5515.07519531 5545.10009766]

下面是我没有得到预期输出的地方。在这里您可以看到嵌套列表没有展平,并且只要存在 2 个或更多元素,就不会计算平均值。

type of group is <class 'list'>
[[1355.59997558594], [1363.0], [1372.05004882812]]
size of group is 3
Below are the values
[[1355.59997559]
 [1363.        ]
 [1372.05004883]]


type of group is <class 'list'>
[[1349.15002441406, 1351.5], [1358.90002441406, 1359.0]]
size of group is 2
Below are the values
[[1349.15002441 1351.5       ]
 [1358.90002441 1359.        ]]

如果您需要一个列表作为输出,我认为 map 可以:

def map_f(x):
    return list(map(np.mean,x))

尝试:

map_f([[1914.05004882812], [1930.65002441406, 1934.5]])
[1350.3250122070299, 1358.9500122070299]

map_f([[1349.15002441406, 1351.5], [1358.90002441406, 1359.0]])
[1350.3250122070299, 1358.9500122070299]

map_f([[1355.59997558594], [1363.0], [1372.05004882812]])
[1355.59997558594, 1363.0, 1372.05004882812]