Subsetting Pandas dataframe based on Boolean condition – why doesn't order matter?

My question is on Python pandas. Suppose we have pandas dataframe df with two columns "A" and "B". I subset to select all values of column "B" where the entries of column "A" are equal to "value". Why does the order of the following commands not matter?

df[df["A"]=="value"]["B"]

Returns the same as the code

df["B"][df["A"]=="value"]

Can you please explain why these work the same? Thanks.

>Solution :

The df["A"]=="value part of your code returns a pandas Series containing Boolean values in accordance to the condition ("A" == "value").
By puting a series mask (a filter, basically) on your DataFrame returns a DataFrame containining only the values on the rows where you’ve had True in your Series mask.
So, in your first code ( df[df["A"]=="value"]["B"] ), you are applying the specific mask on the dataframe, obraining only the rows where the column "A" was equal to "value", then you are extracting the "B" column from your DataFrame.
In your second code, you are first selecting the column "B", then you are selecting only the rows where the column "A" == "value" in the initial DataFrame.
Hope this helps!

Leave a Reply