Why does using "==" return a Series instead of bool in pandas?
It is testing each element of data.categ
for equality with cat
. That produces a vector of True/False values. This is passed as in indexer to data[]
, which returns the rows from data
that correspond to the True values in the vector.
To summarize, the whole expression returns the subset of rows from data
where the value of data.categ
equals cat
.
(Seems possible the whole operation could be done more elegantly using data.groupBy('categ').apply(someFunc)
.)
Yes, it is a test. Boolean expressions are not restricted to if
statements.
It looks as if data
is a data frame (PANDAS). The expression used as a data frame index is how PANDAS denotes a selector or filter. This says to select every row in which the fieled categ
matches the variable cat
(apparently a pre-defined variable). This collection of rows becomes a new data frame, subset
.
It creates a boolean series with indexes where data.categ
is equal to cat
, with this boolean mask, you can filter your dataframe, in other words subset
will have all records where the categ
is the value stored in cat
.
This is an example using numeric data
np.random.seed(0)
a = np.random.choice(np.arange(2), 5)
b = np.random.choice(np.arange(2), 5)
df = pd.DataFrame(dict(a = a, b = b))
df[df.a == 0].head()
# a b
# 0 0 0
# 2 0 0
# 4 0 1
df[df.a == df.b].head()
# a b
# 0 0 0
# 2 0 0
# 3 1 1