pandas 熊猫如何删除交替行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33634142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:12:26  来源:igfitidea点击:

Pandas how to delete alternate rows

pythonpandas

提问by Ashwin Jayarama

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

我有一个带有重复 ID 的 Pandas 数据框。下面是我的数据框

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

如何仅删除具有该类型的行 Low

回答by EdChum

You can also just slice your df using iloc:

您也可以使用iloc以下方法对 df 进行切片:

df.iloc[::2]

This will step every 2 rows

这将每 2 行步进一次

回答by AntonyBrd

You can try this way :

你可以试试这种方式:

df = df[df.type != "Low"]

回答by Leb

Another possible solution is to use drop_duplicates

另一种可能的解决方案是使用 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.

这样您就不必重新分配它。