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

Patricia Arquette
Release: 2024-11-01 18:06:02
Original
583 people have browsed it

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])
Copy after login

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
Copy after login

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

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

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!