slicing a 2d numpy array

Question:

The following code:

import numpy as p
myarr=[[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6]]
copy=p.array(myarr)
p.mean(copy)[:,1]

Is generating the following error message:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    p.mean(copy)[:,1]
IndexError: 0-d arrays can only use a single () or a list of newaxes (and a single ...) as an index

I looked up the syntax at this link and I seem to be using the correct syntax to slice. However, when I type

copy[:,1]

into the Python shell, it gives me the following output, which is clearly wrong, and is probably what is throwing the error:

array([1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6])

Can anyone show me how to fix my code so that I can extract the second column and then take the mean of the second column as intended in the original code above?

EDIT:

Thank you for your solutions. However, my posting was an oversimplification of my real problem. I used your solutions in my real code, and got a new error. Here is my real code with one of your solutions that I tried:

    filteredSignalArray=p.array(filteredSignalArray)

    logical=p.logical_and(EndTime-10.0<=matchingTimeArray,matchingTimeArray<=EndTime)
    finalStageTime=matchingTimeArray.compress(logical)
    finalStageFiltered=filteredSignalArray.compress(logical)

    for j in range(len(finalStageTime)):
        if j == 0:
            outputArray=[[finalStageTime[j],finalStageFiltered[j]]]
        else:
            outputArray+=[[finalStageTime[j],finalStageFiltered[j]]]

    print 'outputArray[:,1].mean() is:  ',outputArray[:,1].mean()

And here is the error message that is now being generated by the new code:

File "mypathmyscript.py", line 1545, in WriteToOutput10SecondsBeforeTimeMarker
    print 'outputArray[:,1].mean() is:  ',outputArray[:,1].mean()
TypeError: list indices must be integers, not tuple

Second EDIT:

This is solved now that I added:

    outputArray=p.array(outputArray)

above my code.

I have been at this too many hours and need to take a break for a while if I am making these kinds of mistakes.

Asked By: MedicalMath

||

Answers:

You probably mean p.mean(copy[:,1]) with the indexing before the mean() function call. I don’t see the problem with the contents of copy – it looks right to me.

Answered By: Michael Koval
x = numpy.array(myarr)
x[:,1].mean()

or

numpy.array(myarr)[:,1].mean()

or if you really hate yourself,

numpy.array(myarr).mean(axis=0)[1]

or

float(sum(a[1] for a in myarr))/len(myarr)
Answered By: Steve Tjoa