How to Select Rows Based on a Logical Condition in Pandas (Python)

preview_player
Показать описание
↓ Code Available Below! ↓

This video shows how to select the rows of a data frame based on a logical condition, such as whether the value of a column conform to a given logical expression. Filtering or subsetting the rows of a data frame by the values of one or more columns is a common an useful operation that you'll perform regularly when cleaning, manipulating and exploring data.

If you find this video useful, like, share and subscribe to support the channel!

Code used in this Python Code Clip:

data = pd.DataFrame({"character": ["Goku","Vegeta", "Nappa","Gohan",
"Piccolo","Tien","Yamcha", "Krillin"],
"power_level": [12000, 16000, 4000, 1500, 3000,
2000, 1600, 2000],
"uniform color": ["orange", "blue", "black", "orange",
"purple", "green", "orange", "orange"],
"species": ["saiyan","saiyan","saiyan","half saiyan",
"namak","human","human","human"]})

data

# Create a logical index with one value for each row
logical_index = data["power_level"] > 2000

logical_index

# Use the logical index to index into the data frame
data[logical_index]

# Select rows based on multiple logical conditions

logical_condition_1 = data["power_level"] > 2000
logical_condition_2 = data["species"] != "saiyan"

data[logical_condition_1 & logical_condition_2]

* Note: YouTube does not allow greater than or less than symbols in the text description, so the code above will not be exactly the same as the code shown in the video! I will use Unicode large < and > symbols in place of the standard sized ones. .

Рекомендации по теме
Комментарии
Автор

Code used in this Python Code Clip:

data = pd.DataFrame({"character": ["Goku", "Vegeta", "Nappa", "Gohan",
"Piccolo", "Tien", "Yamcha", "Krillin"],
"power_level": [12000, 16000, 4000, 1500, 3000,
2000, 1600, 2000],
"uniform color": ["orange", "blue", "black", "orange",
"purple", "green", "orange", "orange"],
"species": ["saiyan", "saiyan", "saiyan", "half saiyan",
"namak", "human", "human", "human"]})

data

# Create a logical index with one value for each row
logical_index = data["power_level"] > 2000

logical_index

# Use the logical index to index into the data frame
data[logical_index]

# Select rows based on multiple logical conditions

logical_condition_1 = data["power_level"] > 2000
logical_condition_2 = data["species"] != "saiyan"

data[logical_condition_1 & logical_condition_2]

DataDaft
Автор

The way you discribe very easy to understand.

SudhirKumar-rygk
Автор

I can’t believe you made this video and didn’t filter for a power level of 9000.

lambaseded