1

I have a big numpy array and want to take the mean of the second columns of each two rows and save the array as a new one. I want to take the mean of each two row, i.e. the mean of second column of of rows 1 and 2. Then, mean of second column of rows 3 and 4, and so on. Then, I want to merge each two rows as a single one. First and third columns of this paired rows are also the same. This is my simplified array:

input= np.array ([[1., 2., 5.],
                  [1., 4., 5.],
                  [4., 10., 3.],
                  [4., 2., 3.],
                  [1., 0., 0.],
                  [1., 1., 0.]])

Then, I want to get:

output= np.array ([[1., 3., 5.],
                   [4., 6., 3.],
                   [1., 0.5, 0.]])

I tried the following but it was not successful at all:

output=np.array([])
for i in range (len(input)-1):
    g=(input[i,1]+input[i+1,1])/2
    output=np.append(g,output)

In advance, I do appreciate any help.

4 Answers 4

2

For two rows, I find it easier to do:

(arr[::2] + arr[1::2])/2
Sign up to request clarification or add additional context in comments.

Comments

2

A little more robust method for reshape, using the input shape

i= np.array ([[1., 2., 5.],
              [1., 4., 5.],
              [4., 10., 3.],
              [4., 2., 3.],
              [1., 0., 0.],
              [1., 1., 0.]])

i.reshape(-1, 2, i.shape[-1]).mean(1)

array([[1. , 3. , 5. ],
       [4. , 6. , 3. ],
       [1. , 0.5, 0. ]])

2 Comments

Dear @Daniel F, Thanks for the solution. It is exactly what I wanted. I do appreciate it.
Be sure to mark solved (the little checkmark) then.
1

You could reshape and find the mean, as follows:

import numpy as np

ipt = np.array([[1., 2., 5.],
                [1., 4., 5.],
                [4., 10., 3.],
                [4., 2., 3.],
                [1., 0., 0.],
                [1., 1., 0.]])
result = np.mean(ipt.reshape((3, 2, 3)), axis=1)
print(result)

Output

[[1.  3.  5. ]
 [4.  6.  3. ]
 [1.  0.5 0. ]]

As a side note, avoid using input as a variable name as it shadows the built-in input.

2 Comments

Dear Dani Mesejo, Thanks for devoting time to my problem. I do appreciate it. But, I colud not run your solution for my big array. I was giving me a reshape error.
You need to change the dimensions to fit it accordingly, in this regar the solution of @DanielF is better.
1

Take even rows (ipt[::2]), odd rows (ipt[1::2]), add them and divide by 2:

output = (ipt[::2] + ipt[1::2])/2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.