![]() |
VOOZH | about |
Excluding columns in a Pandas DataFrame is a common operation when you want to work with only relevant data. In this article, we will discuss various methods to exclude columns from a DataFrame, including using .loc[], .drop(), and other techniques.
We can exclude a column by its location using the .loc [] function. The code below demonstrates how to exclude a specific column by comparing column names.
Output:
DataFrame after excluding 'cost' column using .loc[]
food_id name city
0 1 idly delhi
1 2 dosa goa
2 3 poori hyd
3 4 chapathi chennai
.isin() function.Output
city cost
0 delhi 12
1 goa 34
2 hyd 21
3 chennai 23
Other methods to exclude columns in Pandas, apart from using DataFrame.loc[], are discussed below:
Although .remove() is not a direct Pandas method, we can use it with a list of column names before reassigning the DataFrame.
Output
food_id name city
0 1 idly delhi
1 2 dosa goa
2 3 poori hyd
3 4 chapathi chennai
drop() method is one of the most common ways to exclude specific columns by name:
Output
food_id name city
0 1 idly delhi
1 2 dosa goa
2 3 poori hyd
3 4 chapathi chennai
select_dtypes()We can exclude columns based on their data type using the select_dtypes() method.
Output
name city
0 idly delhi
1 dosa goa
2 poori hyd
3 chapathi chennai
If we need to exclude columns dynamically based on a condition, we can use list comprehensions. For example, to exclude columns whose names start with a specific letter:
Output
food_id name
0 1 idly
1 2 dosa
2 3 poori
3 4 chapathi
These techniques make column exclusion in Pandas flexible and straightforward, helping us focus on the data we need.