Delete Columns Pandas Code Example

Snippet 1

  df.drop(columns=['B', 'C']) 

Snippet 2

  df.drop([‘feature_1’,’feature_2’], inplace = True, axis = 1)  

Snippet 3

  df = df.drop(['B', 'C'], axis=1) 

Snippet 4

  df = pd.DataFrame(np.arange(12).reshape(3, 4),
...                   columns=['A', 'B', 'C', 'D'])
>>> df
   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

Drop columns

df.drop(['B', 'C'], axis=1)
   A   D
0  0   3
1  4   7
2  8  11
df.drop(columns=['B', 'C'])
   A   D
0  0   3
1  4   7
2  8  11
Drop a row by index

df.drop([0, 1])
   A  B   C   D
2  8  9  10  11 

Snippet 5

  df = df.drop(df.columns[[0, 1, 3]], axis=1)  # df.columns is zero-based pd.Index 
df.drop(['column_nameA', 'column_nameB'], axis=1, inplace=True) 

Snippet 6

  df = df.drop(df.columns[[0, 1, 3]], axis=1) 

Copyright © Code Fetcher 2020

 

 

Leave a comment

Your email address will not be published. Required fields are marked *