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

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

Channel:
Subscribers:
53,100
Published on ● Video Link: https://www.youtube.com/watch?v=3WtsZ1OxtfU



Category:
Vlog
Duration: 2:05
2,528 views
38


↓ Code Available Below! ↓

This video shows how to select columns of a data frame based on a logical condition. Filtering or subsetting the columns of a data frame based on a logical check is not quite as common as filtering rows, but it can still be useful operation if you are only interested in variables that conform to certain conditions.

If you find this video useful, like, share and subscribe to support the channel!
► Subscribe: https://www.youtube.com/c/DataDaft?sub_confirmation=1


Code used in this Python Code Clip:

import pandas as pd

import statsmodels.api as sm #(To access mtcars dataset)
mtcars = sm.datasets.get_rdataset("mtcars", "datasets", cache=True).data
mtcars.head()

# Create a logical index with one value for each column
logical_index = mtcars.mean() > 10

logical_index

# Get the corresponding columns
cols = mtcars.columns[logical_index]

# Use the column list to index the data frame
mtcars_sub = mtcars[cols]

mtcars_sub.head()

# Do logical indexing on columns in one line:

mtcars[mtcars.columns[mtcars.mean() > 10]].head()


* 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. .


⭐ Kite is a free AI-powered coding assistant that integrates with popular editors and IDEs to give you smart code completions and docs while you’re typing. It is a cool application of machine learning that can also help you code faster! Check it out here: https://www.kite.com/get-kite/?utm_medium=referral&utm_source=youtube&utm_campaign=datadaft&utm_content=description-only







Tags:
pandas subset columns
pandas logical index on columns
pandas logical mask over columns
pandas data frame subset
pandas data frame logical index
pandas basics
python for data analysis
pandas data manipulation
learn pandas
learn python
pandas select columns based on a condition
pandas subset columns by a condition
pandas logical index over columns
pandas subsetting
pandas filtering columns