【问题标题】:Pandas dataframe: drop all the rows based one column value with pythonPandas 数据框:使用 python 删除基于一列值的所有行
【发布时间】:2016-12-16 04:46:42
【问题描述】:

我有一个数据框 df 如下,我想删除或删除名称为 tom 的行,我使用以下代码(python3):

df1[~df1['name'].str.contains('tom')]

但有错误:

AttributeError: Cannot access attribute 'str' of 'SeriesGroupBy'   
     objects, try using the 'apply' method


name    age weight 
tom     10   40
lucy    15   50
john    20   60
tom     10   40
lucy    15   50
john    20   60
tom     10   40
kate    30   70
tick    40   75
bruce   50   75

请帮我解决,这只是示例数据,因为真实的数据框很大。如果你们有快速的解决方案,请告诉我。提前致谢!

【问题讨论】:

  • 错误是说df1SeriesGroupBy 对象,而不是DataFrame。显然,具有nameageweight 列的 DataFrame 不是df1

标签: pandas dataframe python-3.5


【解决方案1】:

试试这个:

df[df["name"] != 'tom']

 or 

df[~df['name'].str.contains('tom')]

To remove on multiple criteria  -- "~" is return opposite of True/False

df2[~(df2["name"].isin(['tom','lucy']))]

【讨论】:

  • 您好,感谢您的回答,但出现错误:KeyError: 'Column not found: True'
  • 嗨@Merlin,删除名为 tom 和 lucy 的行怎么样。你能再帮我一次吗!
  • @tktktk071,检查编辑...这里是教程...。people.duke.edu/~ccc14/sta-663/…
猜你喜欢
  • 2018-10-17
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 2022-12-12
  • 2017-01-03
相关资源
最近更新 更多