简体   繁体   English

numpy的嵌套列表理解

[英]Nested list comprehension for numpy

I have an issue that I can't seem to resolve. 我有一个似乎无法解决的问题。

I am building in a numpy array of shape (100, 30) from lines of a file (100 lines of 30 values each), and I need to make this array into a shape (100, ) with as values the mean of the n last values from each line of the original array. 我正在从文件的行(每100行包含30个值的行)中构建一个形状为(100,30)的numpy数组,我需要将此数组转换为形状(100,),其中n为均值来自原始数组每一行的最后一个值。

I have as a goal to do this in one line, so I tried nested list comprehensions but I feel totally lost in there and I'm not sure of what I am doing. 我的目标是在同一行中完成此操作,因此我尝试了嵌套列表推导,但是我觉得完全迷失了方向,我不确定自己在做什么。

This is what I got so far, this gives me a correctly shape array but with (I believe) the wrong values. 这就是我到目前为止所得到的,这为我提供了一个正确的形状数组,但具有(我相信)错误的值。

def perf_n_last(n):
    a = np.array([np.mean([i for j in range(len(i)-1, len(i)-(n+1), -1)]) for i in np.loadtxt('myfile.txt')])
    print(a.shape) #outputs (100, )

The input and output should look like: 输入和输出应类似于:

input_f = [[1. 2. 3. 4. 5.]
           [2. 3. 4. 5. 6.]
           [3. 4. 5. 6. 7.]]
#We assume n = 2
output_f = [4.5 5.5 6.5]

I am also open to suggestions about list slices. 我也乐于接受有关列表切片的建议。 Thank you for the help! 感谢您的帮助!

If I'm understanding your question correctly, this can actually be done very quickly with numpy, assuming each row in the 2d array is the same length: 如果我正确理解了您的问题,那么使用numpy可以非常快速地完成此操作,假设2d数组中的每一行的长度都相同:

def perf_n_last(n):
    return np.loadtxt("myfile.txt")[:,-n:].mean(1)

which loads the file, slices to include all rows but only the n last columns, and takes the mean of each resulting row. 加载文件,切片以包括所有行,但仅包括最后n列,并取每个结果行的平均值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM