Pandas: How to Pop Rows from DataFrame


You can use the pop() function to quickly remove a column from a pandas DataFrame.

In order to use the pop() function to remove rows, you must first transpose the DataFrame and then use the pop() function to remove the columns (i.e. the rows of the original DataFrame):

#pop the row in index position 3
df.T.pop(3)

The following example shows how to use this syntax in practice.

Example: Pop Rows from pandas DataFrame

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F'],
                   'points': [18, 22, 19, 14, 14, 11],
                   'assists': [5, 7, 7, 9, 12, 9]})

#view DataFrame
print(df)

  team  points  assists
0    A      18        5
1    B      22        7
2    C      19        7
3    D      14        9
4    E      14       12
5    F      11        9

Now suppose we would like to remove the row in index position 3 of the DataFrame.

We can transpose the DataFrame and then use the pop() function to remove the row in index position 3:

#define transposed DataFrame
df_transpose = df.T

#remove row in index position 3 of original DataFrame
df_transpose.pop(3)

team        D
points     14
assists     9
Name: 3, dtype: object

We can then transpose the DataFrame once again to get back the original DataFrame with one row removed:

#transpose back to original DataFrame
df = df_transpose.T

#view updated DataFrame
print(df)

  team points assists
0    A     18       5
1    B     22       7
2    C     19       7
4    E     14      12
5    F     11       9

Notice that the row in index position 3 has been removed from the DataFrame.

All other rows in the DataFrame remain untouched.

Note: You can find the complete documentation for the pop() function in pandas here.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Insert a Row Into a Pandas DataFrame
How to Drop First Row in Pandas DataFrame
How to Drop Rows in Pandas DataFrame Based on Condition

Leave a Reply

Your email address will not be published.