Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop a list of rows from Pandas dataframe?

Tags:

python

pandas

I have a dataframe df :

>>> 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 

Then I want to drop rows with certain sequence numbers which indicated in a list, suppose here is [1,2,4], then left:

                  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 

How or what function can do that ?

like image 954
bigbug Avatar asked Feb 02 '13 12:02

bigbug


People also ask

How do I drop a list from a DataFrame?

To drop a row or column in a dataframe, you need to use the drop() method available in the dataframe. You can read more about the drop() method in the docs here. Rows are labelled using the index number starting with 0, by default. Columns are labelled using names.

How do I delete multiple rows in a data frame?

To delete rows and columns from DataFrames, Pandas uses the “drop” function. To delete a column, or multiple columns, use the name of the column(s), and specify the “axis” as 1. Alternatively, as in the example below, the 'columns' parameter has been added in Pandas which cuts out the need for 'axis'.

How to drop a list from a DataFrame in Python?

DataFrame. drop() method you can remove/delete/drop the list of rows from pandas, all you need to provide is a list of rows indexes or labels as a param to this method. By default drop() method removes the rows and returns a copy of the updated DataFrame instead of replacing the existing referring DataFrame.

How do you drop 10 rows in pandas?

Using iloc[] to Drop First N Rows of DataFrameUse DataFrame. iloc[] the indexing syntax [n:] with n as an integer to select the first n rows from pandas DataFrame. For example df. iloc[n:] , substitute n with the integer number specifying how many rows you wanted to delete.


1 Answers

Use DataFrame.drop and pass it a Series of index labels:

In [65]: df Out[65]:         one  two one      1    4 two      2    3 three    3    2 four     4    1   In [66]: df.drop(df.index[[1,3]]) Out[66]:         one  two one      1    4 three    3    2 
like image 100
tzelleke Avatar answered Oct 29 '22 23:10

tzelleke