Q:

Selecting/excluding sets of columns in pandas

belongs to collection: Python Pandas Programs

0

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Suppose we want to display all the columns except some specified columns, DataFrame.loc() helps us to achieve this task.

Syntax:

DataFrame.loc[:, df.columns!= 'column_name']

Here, the DataFrame.loc() property will read the sliced index, colon (:) means starting from the first column, DataFrame.columns will return all the columns of a DataFrame and define a specified column name after the conditional operator (!=) will return all the column names except the one which is specified inside the method.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Let us understand with the help of an example:

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Roll_no': [ 1,2,3,4,5],
    'Name': ['Abhishek', 'Babita','Chetan','Dheeraj','Ekta'],
    'Gender': ['Male','Female','Male','Male','Female'],
    'Marks': [50,66,76,45,80],
    'Standard': ['Fifth','Fourth','Third','Third','Third']
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n\n")

Output:

Output 1: Selecting sets of columns

Now, we will print the DataFrame by excluding some columns

# 1] Display columns according to our requirements

print(df.loc[:,df.columns!='Standard'])

Output 1:

Output 2: Selecting sets of columns

# 2] Display columns according to our requirements

print(df.loc[:,df.columns!='Gender'])

Output 2:

Output 3: Selecting sets of columns

# 3] Display columns according to our requirements

print(df.loc[:,df.columns!='Roll_no'])

Output 3:

Output 4: Selecting sets of columns

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to use pivot function in a pandas DataFrame?... >>
<< Python Pandas: Conditional creation of a series/Da...