Ugohihi
Ugohihi

Reputation: 25

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.

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!

Upvotes: 0

Views: 338

Answers (1)

mackenziedg
mackenziedg

Reputation: 48

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:

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.

Upvotes: 3

Related Questions