3

I'm a newbie at numpy, but I was of that notion that you should not iterate over numpy arrays as this defies the purpose of numpy.

I'm trying to perform elementwise operations on a numpy array, but I don't understand the syntax apparantly:

Code:

for line in fidNNC:
    temp = line.strip().split()
    temp.insert(0,0)
    CC.append(temp[0:7])

fidNNC.close()
NNC = np.array(CC)
del(CC)

inds = np.arange(len(NNC))[ NNC[:,4]-1 == NNC[:,1] ]
NNCX = NNC[inds,:]
inds = np.arange(len(NNC))[ NNC[:,5]-1 == NNC[:,2] ]
NNCY = NNC[inds,:]

The file fidNNC contains about a million rows and ten columns of ints.

Error message:

    inds = np.arange(len(NNC))[ NNC[:,4]-1 == NNC[:,1] ]
TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'int'

How do I subtract 1 from each and every one element of NNC[:,4] and NNC[:,5] without iterating?

Thanks in advance,

Daniel

2
  • Ahh, I should read that question/answer closely, looked similar to my problem. NNC.dtype = |S3 Commented Jul 3, 2013 at 13:58
  • Which I was guessing after looking at your code again :) I removed the comment and added an answer. Commented Jul 3, 2013 at 13:59

2 Answers 2

1

You are not converting to int when reading the file, thus the created array has the string type. Convert to int and it should work:

for line in fidNNC:
    temp = [int(i) for i in line.strip().split()]
    temp.insert(0,0)
    CC.append(temp[0:7])
Sign up to request clarification or add additional context in comments.

Comments

0

You can deconstruct the matrix by column and perform operations on the columns you like and re-create, np.c_ allows this. For example a matrix x we can subtract 1 from the first column like so (and place result in z)

z = np.c_[ (x[:,1] - 1), x[:,1:] ]

This pulls out the first column on x, elementwise subtraction on that column and concatenates the rest of the untouched columns. To do two columns simply break up further

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.