Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PANDAS drop a range of rows from df

Tags:

I want to drop m number of rows from the bottom of a data frame. It is integer indexed (with holes). How can this be done?

pandas == 0.10.1 python == 2.7.3

like image 855
beets Avatar asked Mar 29 '13 12:03

beets


People also ask

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.

How do I drop multiple rows in a DataFrame in Python?

Delete a Multiple Rows by Index Position in DataFrame As df. drop() function accepts only list of index label names only, so to delete the rows by position we need to create a list of index names from positions and then pass it to drop(). As default value of inPlace is false, so contents of dfObj will not be modified.

How do you delete multiple rows in pandas?

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


2 Answers

Use slice to select the part you want:

df[:-m] 

If you want to remove some middle rows, you can use drop:

df.drop(df.index[3:5]) 
like image 102
HYRY Avatar answered Sep 21 '22 01:09

HYRY


an example where the range you want to drop is indexes between x and y which I have set to 0 and 10

selecting just the locations between 0 and 10 to see the rows to confirm before removing

x=0 # could change x and y to a start and end date y=10  df.loc[x:y] 

selecting the index

df.loc[x:y].index 

so to remove selection from dataframe

df.drop(df.loc[x:y].index, inplace=True) 
like image 34
Julia Cowper Avatar answered Sep 18 '22 01:09

Julia Cowper