Python element wise and

How to get element-wise matrix multiplication (Hadamard product) in numpy?

but both give the result [[19 22], [43 50]] which is the matrix product, not the element-wise product. How can I get the the element-wise product (aka Hadamard product) using built-in functions?

Are you sure a and b aren’t NumPy’s matrix type? With this class, * returns the inner product, not element-wise. But for the usual ndarray class, * means element-wise product.

are a and b numpy arrays? Also, in your question above, you are using x and y for computation instead of a and b . Is that just a typo?

Always use numpy arrays, and not numpy matrices. See what the numpy docs say about this. Also note that from python 3.5+, you can use @ for matrix multiplication with numpy arrays, which means there should be absolutely no good reason to use matrices over arrays.

To be picky, a and b are lists. They will work in np.dot ; but not in a*b . If you use np.array(a) or np.matrix(a) , * works but with different results.

4 Answers 4

For elementwise multiplication of matrix objects, you can use numpy.multiply :

import numpy as np a = np.array([[1,2],[3,4]]) b = np.array([[5,6],[7,8]]) np.multiply(a,b) 

However, you should really use array instead of matrix . matrix objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use * for elementwise multiplication:

Читайте также:  Random shuffle python это

If you’re on Python 3.5+, you don’t even lose the ability to perform matrix multiplication with an operator, because @ does matrix multiplication now:

a @ b # matrix multiplication 

Источник

Elementwise and in python list

I have two python lists A and B of equal length each containing only boolean values. Is it possible to get a third list C where C[i] = A[i] and B[i] for 0

@ShamshadAlam You will have to have a loop, either an implicit or an explicit one. Why does it matter?

@DeepSpace It doesn’t matter to me. I just wanted to check whether it is possible without loop or not.

4 Answers 4

I’d recommend you use numpy to use these kind of predicates over arrays. Now, I don’t think you can avoid loops to achieve what you want, but. if you don’t consider mapping or enumerating as a form of looping, you could do something like this (C1):

A = [True, True, True, True] B = [False, False, True, True] C = [x and y for x, y in zip(A, B)] C1 = map(lambda (i,x): B[i] and x, enumerate(A)) C2 = [B[i] and x for i,x in enumerate(A)] print C==C1==C2 

You can do it without an explicit loop by using map , which performs the loop internally, at C speed. Of course, the actual and operation is still happening at Python speed, so I don’t think it’ll save much time (compared to doing essentially the same thing with Numpy, which can not only do the looping at C speed, it can do the and operation at C speed too. Of course, there’s also the overhead of converting between native Python lists & Numpy arrays).

from operator import and_ a = [0, 1, 0, 1] b = [0, 0, 1, 1] c = map(and_, a, b) print c 

Note that the and_ function performs a bitwise and operation, but that should be ok since you’re operating on boolean values.

Источник

Python numpy element wise logical and code example

array_like Optional **kwargs For other keyword-only arguments Required Returns: y : ndarray or bool — Boolean result with the same shape as x1 and x2 of the logical AND operation on corresponding elements of x1 and x2. numpy.logical_and() function The logical_and() function is used to compute the truth value of x1 AND x2 element-wise.

Numpy.logical_or() in Python

numpy.logical_or(arr1, arr2, out=None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘logical_or’) : This is a logical function and it helps user to find out the truth value of arr1 OR arr2 element-wise. Both the arrays must be of same shape.

Parameters :

arr1 : [array_like]Input array.
arr2 : [array_like]Input array.

out : [ndarray, optional]Output array with same dimensions as Input array, placed with result.

**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.

where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.

An array with Boolean results of arr1 OR arr2 element-wise(of the same shape).

Code 1 : Working

Output Array : [ True True True True]

Code 2 : Value Error if input array’s have different shapes

ValueError: operands could not be broadcast together with shapes (4,) (5,)

References :
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.logical_or.html#numpy.logical_or
.

NumPy Logic functions: logical_or() function, Logical OR is applied to the elements of x1 and x2. They have to be of the same shape. A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have …

NumPy Logic functions: logical_and() function

numpy.logical_and() function

The logical_and() function is used to compute the truth value of x1 AND x2 element-wise.

numpy.logical_and(x1, x2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) =

Version: 1.15.0

Name Description Required /
Optional
x1, x2 Input arrays. x1 and x2 must be of the same shape.
array_like
Required
out A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to.
If not provided or None, a freshly-allocated array is returned.
A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
ndarray, None, or tuple of ndarray and None
Optional
where Values of True indicate to calculate the ufunc at that position,
values of False indicate to leave the value in the output alone.
array_like
Optional
**kwargs For other keyword-only arguments Required

Returns:
y : ndarray or bool — Boolean result with the same shape as x1 and x2 of the logical AND operation on corresponding elements of x1 and x2.
This is a scalar if both x1 and x2 are scalars.

NumPy.logical_and() method Example-1:

>>> import numpy as np >>> np.logical_and(True, False) 

NumPy.logical_and() method Example-2:

>>> import numpy as np >>> np.logical_and([True, False], [False, False]) 

NumPy.logical_and() method Example-3:

>>> import numpy as np >>> x = np.arange(6) >>> np.logical_and(x>1, x<4) 
array([False, False, True, True, False, False])

Python - NumPy Code Editor:

Python Numpy - GeeksforGeeks, Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Besides its obvious scientific uses, Numpy can also be used as an efficient multi …

Numpy element-wise comparison using a different array for values

It seems that you want to index indices with the indices in x . Try with:

Here is my approach to the problem:

import numpy as np x = np.array([0, 0, 2, 0, 3, 0, 1, 0, 0, 0, 0, 0, 3, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 3, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 2, 0, 1, 0, 0, 0, 2, 0, 2, 2, 0, 2, 0, 0, 2, 2, 0, 2, 2, 0, 2, 0, 0, 2]) indices = [True, True, False, False] x2 = np.copy(x) x2 = np.array(x2,dtype='object') for i,val in enumerate(x): x2[i] = indices[val] print(x2) 

In case you don't need x later on then you can just do x = np.array(x,dtype='object') instead of using a seperate variable x2 .

[True True False True False True True True True True True True False True False True True True True True True True True True True True True True False True False True True True True True False True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True False True True False True True True True True False True False False True False True True False False True False False True False True True False] 

The above code, on average, took 0.12967189999994844 seconds and Roberto's code took 0.05755720000001929 seconds when tested 5000 times. So you should prefer his code instead.

NumPy: Create an element-wise comparison (equal, Contribute your code (and comments) through Disqus. Previous: Write a NumPy program to create an element-wise comparison (greater, greater_equal, less and less_equal) of two given arrays. Next: Write a NumPy program to create an array with the values 1, 7, 13, 105 and determine the size of the memory …

NumPy logic functions: logical_or() function

numpy.logical_or() function

The logical_or() function is used to compute the truth value of x1 OR x2 element-wise.

numpy.logical_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) =

Version: 1.15.0

Name Description Required /
Optional
x1, x2 Logical OR is applied to the elements of x1 and x2.
They have to be of the same shape.
array_like
Required
out A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to.
If not provided or None, a freshly-allocated array is returned.
A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
ndarray, None, or tuple of ndarray and None
Optional
where Values of True indicate to calculate the ufunc at that position,
values of False indicate to leave the value in the output alone.
array_like
Optional
**kwargs For other keyword-only arguments Required

Returns:
y : ndarray or bool - Boolean result with the same shape as x1 and x2 of the logical OR operation on elements of x1 and x2.
This is a scalar if both x1 and x2 are scalars.

NumPy.logical_or() method Example-1:

>>> import numpy as np >>> np.logical_or(True, False) 

NumPy.logical_or() method Example-2:

>>> import numpy as np >>> np.logical_or([True, False], [False, False]) 

NumPy.logical_or() method Example-3:

>>> import numpy as np >>> x = np.arange(7) >>> np.logical_or(x < 2, x >4) 
array([ True, True, False, False, False, True, True])

Python - NumPy Code Editor:

Numpy element wise division Code Example, Get code examples like "numpy element wise division" instantly right from your google search results with the Grepper Chrome Extension. Follow . GREPPER; SEARCH SNIPPETS; PRICING; FAQ; USAGE DOCS ; INSTALL GREPPER; Log In; All Languages >> Python >> numpy element wise division “numpy element wise …

Источник

Element-wise 'and' for lists in python?

X and Y means if the first item is truthy (which a non-empty list is), evaluate to the value of the second item.

3 Answers 3

This is a perfect opportunity to use map , because and can be represented with a built-in function:

import operator X = [True,False] Y = [True,True] map(operator.and_, X,Y) #=> [True, False] 

The reason why you get the behaviour you did is that and performs operations on the operands as if they had bool applied to them. All non-empty lists evaluate to True in a boolean context.

As to the "list comprehension is always better" point: no it's not. The equivalent list comprehension is:

[x and y for x, y in zip(X, Y)] 

Which has to build an intermediate object (either list or generator, depending on the python version), and still requires the reader to know what zip does, just as much as map does. It's also likely to be slightly slower (because map + builtin function is fast - it all happens in the C layer, essentially). In fact, timeit shows that izip is faster (see below), but I really think the readability point is more important; you may also see different results if performance really matters.

>>> timeit.timeit('map(operator.and_, X,Y)', 'import operator; import itertools; import random; X = [random.choice([True,False]) for _ in range(1000)]; Y = [random.choice([True,False]) for _ in range(1000)]', number=10000) 1.0160579681396484 >>> timeit.timeit('[x and y for x, y in zip(X, Y)]', 'import operator; import itertools; import random; X = [random.choice([True,False]) for _ in range(1000)]; Y = [random.choice([True,False]) for _ in range(1000)]', number=10000) 1.3570780754089355 >>> timeit.timeit('[x and y for x, y in itertools.izip(X, Y)]', 'import operator; import itertools; import random; X = [random.choice([True,False]) for _ in range(1000)]; Y = [random.choice([True,False]) for _ in range(1000)]', number=10000) 0.965054988861084 

That said, if you need arbitrary numbers of lists, you need to use all in a list comprehension (or combined with izip directly); and and_ is technically bitwise and, so be aware that might have funky results if working with numeric types other than bool .

import itertools map(all,itertools.izip(X,Y,Z)) 

Источник

Оцените статью