Python Pandas - How to delete a row from a DataFrame

PythonServer Side ProgrammingProgramming

To delete a row from a DataFrame, use the drop() method and set the index label as the parameter.

At first, let us create a DataFrame. We have index label as w, x, y, and z:

dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],
columns=['a', 'b'])

Now, let us use the index label and delete a row. Here, we will delete a row with index label ‘w’

dataFrame = dataFrame.drop('w')

Example

Following is the code

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],columns=['a', 'b'])

# DataFrame
print"DataFrame...\n",dataFrame

# deleting a row
dataFrame = dataFrame.drop('w')
print"DataFrame after deleting a row...\n",dataFrame

Output

This will produce the following output

DataFrame...
   a   b
w  10  15
x  20  25
y  30  35
z  40  45
DataFrame after deleting a row...
   a   b
x  20  25
y  30  35
z  40  45
raja
Published on 14-Sep-2021 08:16:16
Advertisements