Home > Backend Development > Python Tutorial > How to Drop Rows from a Pandas Dataframe Based on Index or Conditions?

How to Drop Rows from a Pandas Dataframe Based on Index or Conditions?

Linda Hamilton
Release: 2024-11-03 10:50:29
Original
847 people have browsed it

How to Drop Rows from a Pandas Dataframe Based on Index or Conditions?

Dropping Rows from a Pandas Dataframe

In Pandas, we often encounter the need to remove certain rows from a dataframe, either for data cleaning purposes or to focus on specific subsets. One efficient way to achieve this is by utilizing the drop function, which allows us to selectively remove rows based on various criteria.

To demonstrate the process, let's consider a dataframe df:

<code class="python">import pandas as pd

df = pd.DataFrame({'sales': [2.709, 6.590, 10.103, 15.915, 3.196, 7.907],
                   'discount': [None, None, None, None, None, None],
                   'net_sales': [2.709, 6.590, 10.103, 15.915, 3.196, 7.907],
                   'cogs': [2.245, 5.291, 7.981, 12.686, 2.710, 6.459]})

print(df)
</code>
Copy after login

Now, suppose we want to drop rows with certain sequence numbers, represented by a list, such as [1, 2, 4]. To do so, we can use the drop function as follows:

  1. Create a Series of index labels that you wish to remove:
<code class="python">indices_to_drop = [1, 2, 4]</code>
Copy after login
  1. Alternatively, you can also drop rows based on column conditions:
<code class="python">conditions_to_drop = df['sales'] > 10
df = df[~conditions_to_drop]</code>
Copy after login

By specifying the index parameter in drop, we can effectively remove the rows corresponding to the provided indices, leaving us with the desired subset:

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

In this case, it would result in the following dataframe:

                  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 Index or Conditions?. 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