what is ".==" in julia and its equivalent in python?

Viewed 1208

I'm new to julia and I'm working on to rewrite julia code to python code. And I saw the some codes using .== expression. I couldn't understand what this means. So I searched it on web but couldn't find an answer. Can someone tell me what is .== in julia and its equivalent in python?

fyi, it was written like below.

x = sum(y .== 0)  # y is array
2 Answers

That's a Vectorized dot operation and is used to apply the operator to an array. You can do this for one dimensional lists in python via list comprehensions, but here it seems like you are just counting all zeroes, so

>>> y = [0,1,1,1,0]
>>> sum(not bool(v) for v in y)
2

Other packages like numpy or pandas will vectorize operators, so something like this will do

>>> import numpy as np
>>> y = np.array([0,1,1,1,0])
>>> (y == 0).sum()
2
>>>
>>> import pandas as pd
>>> df=pd.DataFrame([[0,1,2,3], [1,2,3,0], [2,3,4,0]])
>>> (df==0).sum()
0    1
1    0
2    0
3    2
dtype: int64
>>> (df==0).sum().sum()
3

What It does:

The dot here is for vectorized operations: dot call

It basically applies your selected operation to each element of your vector (see dot operators).

So in your case, y .== 0 will check equality to 0 for each element of your vector y, meaning x will be the number of values from y being equal to 0.

Python equivalent:

As for how to do the equivalent in python, you can do it "by hand" through list comprehension, or with a library such as numpy. Examples:

x = sum([i == 0 for i in y])

or

import numpy as np
x = sum(np.array(y) == 0)
# or
x = (np.array(y) == 0).sum()
Related