Python ProgrammingPython Programming

How to delete DataFrame columns by name or index in Pandas?

Drop DataFrame Column(s) by Name and Index:

import pandas as pd

employees = pd.DataFrame({
    'EmpCode': ['Emp001', 'Emp002', 'Emp003', 'Emp004', 'Emp005'],
    'Name': ['John', 'Doe', 'William', 'Spark', 'Mark'],
    'Occupation': ['Chemist', 'Statistician', 'Statistician',
                   'Statistician', 'Programmer'],
    'Date Of Join': ['2018-01-25', '2018-01-26', '2018-01-26', '2018-02-26',
                     '2018-03-16'],
    'Age': [23, 24, 34, 29, 40]})

print(employees)

print("\n Drop Column by Name \n")
employees.drop('Age', axis=1, inplace=True)
print(employees)

print("\n Drop Column by Index \n")
employees.drop(employees.columns[[0,1]], axis=1, inplace=True)
print(employees)


C:\python\pandas examples>python example8.py
   Age Date Of Join EmpCode     Name    Occupation
0   23   2018-01-25  Emp001     John       Chemist
1   24   2018-01-26  Emp002      Doe  Statistician
2   34   2018-01-26  Emp003  William  Statistician
3   29   2018-02-26  Emp004    Spark  Statistician
4   40   2018-03-16  Emp005     Mark    Programmer
 
 Drop Column by Name
 
  Date Of Join EmpCode     Name    Occupation
0   2018-01-25  Emp001     John       Chemist
1   2018-01-26  Emp002      Doe  Statistician
2   2018-01-26  Emp003  William  Statistician
3   2018-02-26  Emp004    Spark  Statistician
4   2018-03-16  Emp005     Mark    Programmer
 
 Drop Column by Index
 
      Name    Occupation
0     John       Chemist
1      Doe  Statistician
2  William  Statistician
3    Spark  Statistician
4     Mark    Programmer
 
C:\python\pandas examples>