slicing a 2d numpy array

Posted by MedicalMath on Stack Overflow See other posts from Stack Overflow or by MedicalMath
Published on 2011-01-12T01:14:25Z Indexed on 2011/01/12 1:53 UTC
Read the original article Hit count: 497

Filed under:
|
|
|
|

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 "mypath\myscript.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.

© Stack Overflow or respective owner

Related posts about python

Related posts about arrays