如何获得一维数组和二维数组的平均值?

问题描述

这里有两个列表:list = [[1,2],[3,4]] 和 list = [1,2,3,4]

我想计算列表的平均值。这是我迄今为止的代码输出

 def summary(x):
      mean1 = np.mean(x)

      Dict = {"mean":mean1}
 return Dict

summary([1,4])
My output is == {'mean': 2.4}

summary([[1,4]])
My output is == error

我只想知道我应该对代码进行哪些更改,以便在我将其作为输入而不仅仅是一维数组时二维数组也可以工作?

我已经看到我应该插入 (x,axis=1) 但它只适用于 2Darray 而不适用于 1D 数组。

我希望 2D mean 给我输出:'mean': [1.5,3.5]

解决方法

摘要定义中有错误,而不是您希望将 list 作为参数的 x

有了这个,它对我来说很好用:

import numpy as np
def summary(x):
    mean1 = np.mean(x)

    Dict = {"mean":mean1}
    return Dict

a = summary([1,2,3,4])
print(a)
b = summary([[1,2],[3,4]])
print(b)

结果是:

{'mean': 2.4}
{'mean': 2.5}

[更新]

如果您想沿特定轴获得平均值,您可以按照以下方式进行操作。您必须检查阵列形状,因为您希望它在方向 1 上,这对于一维阵列来说是不存在的。

import numpy as np
def summary(x):
    arr = np.array(x)
    if len(arr.shape) == 2:
        mean1 = np.mean(arr,axis=1)
    else:
        mean1 = np.mean(arr)

    Dict = {"mean":mean1}
    return Dict

a = summary([1,4]])
print(b)

哪个返回

{'mean': 2.4}
{'mean': array([1.5,3.5])}
,

试试这个:

import boto3
from botocore.exceptions import ClientError


def get_secret():
    secret_name = "MySecretName"
    region_name = "us-west-2"

    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',region_name=region_name,)

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            print("The requested secret " + secret_name + " was not found")
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            print("The request was invalid due to:",e)
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            print("The request had invalid params:",e)
        elif e.response['Error']['Code'] == 'DecryptionFailure':
            print("The requested secret can't be decrypted using the provided KMS key:",e)
        elif e.response['Error']['Code'] == 'InternalServiceError':
            print("An error occurred on service side:",e)