indicates whether we should delete rows or columns.
df1.drop(["Row 2", "Row 4"], axis=0, inplace=True)
If axis=0, then rows with the mentioned labels are deleted. If axis=1, then columns with the mentioned labels are deleted. And the last parameter inplace=True indicates that we do not want to create a new DataFrame after the deletion. Instead, the original DataFrame gets updated.
How to delete columns from an existing DataFrame using Python pandas?
We can use the following Python code to delete columns from an existing DataFrame using Python pandas.
import pandas
list1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
df1 = pandas.DataFrame(list1, index=["Row 1", "Row 2", "Row 3", "Row 4"], columns=["Column 1", "Column 2", "Column 3", "Column 4"])
print("df1 before deletion of columns: \n", df1)
df1.drop(["Column 1", "Column 4"], axis=1, inplace=True)
print("df1 after deletion of columns: \n", df1)
The output of the above program will be:
df1 before deletion of columns:
Column 1 Column 2 Column 3 Column 4
Row 1 1 2 3 4
Row 2 5 6 7 8
Row 3 9 10 11 12
Row 4 13 14 15 16
df1 after deletion of columns:
Column 2 Column 3
Row 1 2 3
Row 2 6 7
Row 3 10 11
Row 4 14 15
Please note that in the drop() function, we are providing the labels of the columns that should be deleted like before. Here, columns are deleted. So, axis is 1.
df1.drop(["Column 1", "Column 4"], axis=1, inplace=True)
And the inplace parameter is True. It indicates we do not want to create a new DataFrame after deletion. Instead, the existing DataFrame will be updated.








































0 Comments