How to Delete a Column from a Pandas Dataframe Object in Python



Python


In this article, we show how to delete a column from a pandas dataframe object in Python.

So if you have an existing pandas dataframe object, you are free to do many different modifications, including adding columns or rows to the dataframe object, deleting columns or rows, updating values, etc.

We will show in this article how you can delete a column from a pandas dataframe object in Python.

So below we create a dataframe object that has columns, 'W', 'X', and 'Y'.

We will show how you can permanently delete a column.

In the code below, we permanently delete the 'Y' column from the dataframe.



So let's now go over the code.

So we first have to import the pandas module. We do this with the line, import pandas as pd.

as pd means that we can reference the pandas module with pd instead of writing out the full pandas each time.

We import rand from numpy.random, so that we can populate the DataFrame with random values. In other words, we won't need to manually create the values in the table. The randn function will populate it with random values.

We create a variable, dataframe1, which we set equal to, pd.DataFrame(randn(4,3),['A','B','C','D',],['X','Y','Z'])

This creates a DataFrame object with 4 rows and 3 columns.

The rows are 'A', 'B', 'C', and 'D'.

The columns are 'W', 'X', and 'Y'.

After we output the dataframe1 object, we get the DataFrame object with all the rows and columns, which you can see above.

We then delete the 'Y' column from the dataframe1 dataframe object.

We delete a column from a dataframe object using the drop() function.

Inside of this drop() function, we specify the column that we want to delete, in this case, it's the 'Y' column.

Also, to delete a column, we must specify, axis=1

axis is an attribute in the drop() function that refers to either a row or a column. To refer to a row, we specify, axis=0. To specify a column, we specify, axis=1

By default, axis=0, so in order to delete a row, you don't have to specify the axis attribute. However, to delete a column, you do have to specify, axis=1, since axis=0 by default.

After this, we also have to specify, inplace=True

What this line does is it allows the deletion to be permanent.

If you don't specify, inplace=True, then the deletion will not be permanent.

So after we run this line and output the dataframe1 object, you see that the column 'Y' is now deleted from the dataframe object.

So this is how to delete a column from a pandas dataframe object in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...