Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas how to delete alternate rows [duplicate]

Tags:

python

pandas

I have a pandas dataframe with duplicate ids. Below is my dataframe

id  nbr  type  count 
7   21   High     4  
7   21   Low      6    
8   39   High     2    
8   39   Low      3    
9   13   High     5    
9   13   Low      7    

How to delete only the rows having the type Low

like image 520
Ashwin Jayarama Avatar asked Nov 10 '15 15:11

Ashwin Jayarama


People also ask

How do I get rid of duplicate rows in pandas?

Remove All Duplicate Rows from Pandas DataFrame You can set 'keep=False' in the drop_duplicates() function to remove all the duplicate rows. For E.x, df. drop_duplicates(keep=False) .

How do you delete alternate rows in Python?

How do I delete all alternate rows? Select all the filtered cells in the helper column (excluding the header) Right-click on any of the selected cells and click on 'Delete Row' In the dialog box that opens, click on OK. This will delete all the visible records and you will only see the header row as of now.

How do you select alternate rows in pandas?

To select the rows, the syntax is df. loc[start:stop:step] ; where start is the name of the first-row label to take, stop is the name of the last row label to take, and step as the number of indices to advance after each extraction; for example, you can use it to select alternate rows.

What does Drop_duplicates do in pandas?

The drop_duplicates() method removes duplicate rows. Use the subset parameter if only some specified columns should be considered when looking for duplicates.


3 Answers

You can also just slice your df using iloc:

df.iloc[::2]

This will step every 2 rows

like image 142
EdChum Avatar answered Oct 18 '22 21:10

EdChum


Another possible solution is to use drop_duplicates

df = df.drop_duplicates('nbr')
print(df)

   id  nbr  type  count
0   7   21  High      4
2   8   39  High      2
4   9   13  High      5

You can also do:

df.drop_duplicates('nbr', inplace=True)

That way you don't have to reassign it.

like image 34
Leb Avatar answered Oct 18 '22 21:10

Leb


You can try this way :

df = df[df.type != "Low"]
like image 5
AntonyBrd Avatar answered Oct 18 '22 22:10

AntonyBrd