13
votes

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
It's called a "vectorized operator" or a "dot operator" in Julia. Take a look at this section from the official documentation and see if it answers your question. - PaSTE
Thank you very much for your advices and answers. I want to upvote, but I can't. So I would like to express my gratitude in words here. - CalmPenguin
A small comment - all the examples in Python are reproducing what isequal does in Julia, as == uses triple-valued logic (so missing is propagated). Also in Julia normally you would not write sum(y .== 0) but rather count(iszero, y) as it will be faster. - Bogumił Kamiński

2 Answers

11
votes

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
5
votes

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()