【问题标题】:How to access specific elements in a list of lists to do the np.mean function?如何访问列表列表中的特定元素以执行 np.mean 函数?
【发布时间】:2021-07-03 23:34:22
【问题描述】:

假设我们要使用三个文件 data1.csv、data2.csv 和 data3.csv。然后,您的函数应获取文件名列表并返回以下内容:

array([[ 11.   11.9  13. ]
       [  9.5   6.8   9.4]
       [  7.2  11.1  12.5]
       [  8.8   7.3   9.2]
       [ 16.6  10.6  10.3]])

例如,左上角单元格中的 11.0 是 7.98631、12.65900 和 12.47115 的平均值(四舍五入到小数点后 1 位)。这些值来自每个 CSV 文件的第一行和第一列。

我已将文件放在一个列表中,但我不知道如何在主列表中每个列表的第一个元素中创建函数 np.mean,然后是每个列表的第二个元素,依此类推。有人可以帮我吗?

我的代码不完整 =(:

    import numpy as np
    
    def mean_datasets(argumentos):
        lista = []
        while int(len(lista)) < int(len(list(argumentos))):
            for files in argumentos:
                dados_txt = np.loadtxt(files, delimiter=',')
                lista.append(dados_txt)
            print(lista)

【问题讨论】:

    标签: python list numpy


    【解决方案1】:

    假设l1l2l3 是从文本文件加载的数组。列出它们(您的lista),转换为 3D numpy 数组,然后简单地计算沿新(第一)维度的平均值:

    np.array([l1, l2, l3]).mean(axis=0)
    

    或者

    np.array(lista).mean(axis=0)
    

    【讨论】:

    • 太棒了!!!!这正是我所需要的! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2012-05-23
    • 2021-10-03
    相关资源
    最近更新 更多