How to Drop Specific Rows from a Pandas DataFrame Using a List of Indices?

DDD
Release: 2024-10-30 21:45:30
Original
618 people have browsed it

How to Drop Specific Rows from a Pandas DataFrame Using a List of Indices?

Dropping Specific Rows from a Pandas Dataframe using a List of Indices

To remove rows from a Pandas dataframe based on specific indices, the DataFrame.drop function is commonly utilized. Let's delve into its usage:

Consider a dataframe df with data on sales, discount, net sales, and COGS:

<code class="python">>>> 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</code>
Copy after login

Now, suppose we want to drop the rows with sequence numbers 1, 2, and 4:

<code class="python">list_of_indices = [1, 2, 4]</code>
Copy after login

To achieve this, we can apply the DataFrame.drop function along with a Series of indices:

<code class="python">df = df.drop(index=list_of_indices)</code>
Copy after login

As a result, the modified df will only contain the remaining rows:

<code class="python">>>> df
                  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</code>
Copy after login

This approach allows us to selectively remove rows from a dataframe based on a specified list of indices, making it a versatile tool for data manipulation in Pandas.

The above is the detailed content of How to Drop Specific Rows from a Pandas DataFrame Using a List of Indices?. 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
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!