In this python pandas program, we will select all columns except one column in a DataFrame using the pandas library.
Steps to solve the program
- Import pandas library as pd.
- Create a dataframe using pd.DataFrame().
- Create a new dataframe that has all columns except the age column using df.loc[:, df.columns != ‘Age’].
- It will select all the rows for all columns except the age column.
- Print the output.
import pandas as pd
import numpy as np
d = {'Sr.no.':[1,2,3,4],'Name':['Alex','John','Peter','Klaus'],'Age':[30,27,29,33],'Salary':[50000,65000,58000,66000]}
df = pd.DataFrame(d)
print(df)
print("All columns except 'Age':")
df = df.loc[:, df.columns != 'Age']
print(df)
Output :
0 Sr.no. Name Age Salary
0 1 Alex 30 50000
1 2 John 27 65000
2 3 Peter 29 58000
3 4 Klaus 33 66000
All columns except 'Age':
Sr.no. Name Salary
0 1 Alex 50000
1 2 John 65000
2 3 Peter 58000
3 4 Klaus 66000