Python Forum
.loc with Booleans - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: .loc with Booleans (/thread-29302.html)



.loc with Booleans - Mark17 - Aug-27-2020

Can someone explain the mechanism of this output?

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
     index=['cobra', 'viper', 'sidewinder'],
     columns=['max_speed', 'shield'])


>>> df.loc[[False,False,True]]
            max_speed  shield
sidewinder          7       8



RE: .loc with Booleans - snippsat - Aug-27-2020

pandas.DataFrame.loc
loc doc Wrote:.loc[] is primarily label based, but may also be used with a boolean array.
So if True(a boolan) is in the list it will get that row or rows.
import pandas as pd

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
     index=['cobra', 'viper', 'sidewinder'],
     columns=['max_speed', 'shield'])

>>> df
            max_speed  shield
cobra               1       2
viper               4       5
sidewinder          7       8

>>> df.loc[[False, True, True]]
            max_speed  shield
viper               4       5
sidewinder          7       8

>>> # Same as
>>> df.loc[['viper', 'sidewinder']]
            max_speed  shield
viper               4       5
sidewinder          7       8