Home  >  Article  >  Backend Development  >  How to Drop Rows from a Pandas Dataframe Based on a List of Index Labels?

How to Drop Rows from a Pandas Dataframe Based on a List of Index Labels?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 18:06:02584browse

How to Drop Rows from a Pandas Dataframe Based on a List of Index Labels?

Dropping Rows from a Pandas Dataframe based on a List

In Pandas, manipulating dataframes often involves dropping rows or columns. One specific scenario arises when you need to remove rows based on a sequence of index labels.

To drop rows from a dataframe based on a list of index labels, you can utilize the DataFrame.drop method. This method allows for the selective removal of data based on specified criteria.

Solution:

In the given example, you have a dataframe df and a list [1, 2, 4] representing the index labels of the rows to be dropped. You can employ DataFrame.drop as follows:

df.drop(index=[1, 2, 4])

This command will generate a new dataframe containing all the rows except those with index labels 1, 2, and 4.

Example:

Consider the provided dataframe df:

                  sales  discount  net_sales    cogs
STK_ID RPT_Date                                     
600141 20060331   2.709       NaN      2.709   2.245
       20060630   6.590       NaN      6.590   5.291
       20060930  10.103       NaN     10.103   7.981
       20061231  15.915       NaN     15.915  12.686
       20070331   3.196       NaN      3.196   2.710
       20070630   7.907       NaN      7.907   6.459

Dropping rows with index labels [1, 2, 4] using DataFrame.drop:

new_df = df.drop(index=[1, 2, 4])

The resulting dataframe new_df will contain the following rows:

                  sales  discount  net_sales    cogs
STK_ID RPT_Date                                     
600141 20060331   2.709       NaN      2.709   2.245
       20061231  15.915       NaN     15.915  12.686
       20070630   7.907       NaN      7.907   6.459

The above is the detailed content of How to Drop Rows from a Pandas Dataframe Based on a List of Index Labels?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn