简体   繁体   中英

Numpy array construction using tuples

C = numpy.array([a^b for a,b in A,B])

Is what I attempted. I thought it would xor each individual element in A and B which are matrices of their own and store it as the same shape within C . How would you do this and where is the flaw in my logic?

EDIT: All values within A and B are ints, an example would be both being shape (3,4) containing a range of integers from 0-10

Direct xor

C = A^B

Resulted in this error:

TypeError: ufunc 'bitwise_xor' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule 'safe'

The TypeError is confusing me as both A and B contain only ints. AI am 100% certain is all ints. B was constructed the following way:

B = np.vstack((A[1:],np.ones(A.shape[1])))

Should this not be all ints as well?

So, your problem is, that np.ones() returns an array containing double values. You can't xor double values with the xor operator from numpy. To solve it, you should use the dtype parameter when creating B, like this example:

import numpy as np

A = np.array([[1,2,3,4],[4,5,6,7],[7,8,9,10]])
B = np.vstack((A[1:], np.ones(A.shape[1], dtype=np.int))) # Change this line.

C = A ^ B

Output:

array([[ 5,  7,  5,  3],
       [ 3, 13, 15, 13],
       [ 6,  9,  8, 11]])

The ^ operator is defined on numpy arrays, if A and B are tuples then:

C = np.array(A) ^ np.array(B)

The xor is done in numpy level and should be super fast.

You are missing the zip to make your current approach work:

C = numpy.array([a ^ b for a, b in zip(A, B)])

but note that there's a much simpler way:

C = A ^ B

Demo:

>>> A = np.array((1, 2, 3, 4))
>>> B = np.array((2, 3, 1, 4))
>>> A ^ B
array([3, 1, 2, 0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM