9951 explained code solutions for 126 technologies


python-pandasHow to remove dataframe column by index


import pandas as pd

df = pd.DataFrame({
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Price': [204, 304, 404, 405, 305],
  'Color': ['red', 'red', 'gray', 'black', 'red']
})

df.drop(df.columns[1], inplace=True, axis=1)ctrl + c
import pandas as pd

load Pandas module

pd.DataFrame

creates Pandas DataFrame object

.drop(

drops selected column from dataframe

df.columns[1]

selects second column (indexes starts from 0)

inplace=True

will remove column and save result to current dataframe variable

axis=1

used to ask Pandas to drop column (not row)


Usage example

import pandas as pd

df = pd.DataFrame({
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Price': [204, 304, 404, 405, 305],
  'Color': ['red', 'red', 'gray', 'black', 'red']
})

df.drop(df.columns[1], inplace=True, axis=1)
print(df)
output
  Phone  Color
0   ip5    red
1   ip6    red
2   ip8   gray
3   sms  black
4    xi    red