search
Search
Guest 0reps
Thanks for the thanks!
close
account_circle
Profile
exit_to_app
Sign out
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview Doc Search Code Search Beta SORRY NOTHING FOUND!
mic
Start speaking... Voice search is only supported in Safari and Chrome.
Shrink
Navigate to
A
A
brightness_medium
share
arrow_backShare Twitter Facebook

# Removing rows using integer index in Pandas DataFrame

Programming
chevron_right
Python
chevron_right
Pandas
chevron_right
Cookbooks
chevron_right
DataFrame Cookbooks
chevron_right
Row and Column Operations Cookbook
schedule Jul 1, 2022
Last updated
local_offer PythonPandas
Tags
expand_more

# Solution

To remove rows using integer index in Pandas DataFrame:

1. get the name of the row index using `iloc`.

2. use the `drop(~)` method to remove the row.

# Removing a single row using integer index

Consider the following DataFrame:

``` df = pd.DataFrame({"A":[2,3,4],"B":[5,6,7]}, index=["a","b","c"])df A Ba 2 5b 3 6c 4 7 ```

To remove row at integer index `1`:

``` df.drop(index=df.iloc.name) A Ba 2 5c 4 7 ```

## Explanation

The `drop(~)` method is used to remove rows and columns, but the caveat is that you can only remove rows/column by their name. Therefore, we first use `iloc` to extract the row at integer index `1`, and then extract its name using the `name` property:

``` df.iloc.name 'b' ```
NOTE

The `drop(~)` method returns a new DataFrame, that is, the original `df` is kept intact. To directly modify the original `df`, set `inplace=True`.

# Removing multiple rows using integer index

Consider the same `df` as above:

``` df = pd.DataFrame({"A":[2,3,4],"B":[5,6,7]}, index=["a","b","c"])df A Ba 2 5b 3 6c 4 7 ```

To remove multiple rows at integer index `0` and `1`:

``` df.drop(index=df.iloc[[0,1]].index) A Bc 4 7 ```

## Explanation

We first extract rows at integer index `0` and `1` as a DataFrame using `iloc`:

``` df.iloc[[0,1]] A Ba 2 5b 3 6 ```

We then fetch the index of this DataFrame using the `index` property:

``` df.iloc[[0,1]].index Index(['a', 'b'], dtype='object') ```

Now that we have the labels of the rows that we want to remove, directly pass this into `drop(~)`:

``` df.drop(index=df.iloc[[0,1]].index) A Bc 4 7 ```
mail