【问题标题】:Remove entries based on group by根据分组删除条目
【发布时间】:2017-06-09 19:53:48
【问题描述】:

我有一个如下所示的数据集:

venue_id,latitude,longitude,venue_category,country_code,user_id,uct_time,time_offset
4af833a6f964a5205a0b22e3,13.693775,100.751152,Airport,TH,4337,Tue Apr 03 20:35:48 +0000 2012,420
4af833a6f964a5205a0b22e3,13.693775,100.751152,Airport,TH,101773,Tue Apr 03 20:46:53 +0000 2012,420
4af833a6f964a5205a0b22e3,13.693775,100.751152,Airport,TH,105093,Tue Apr 03 22:39:56 +0000 2012,420
4af833a6f964a5205a0b22e3,13.693775,100.751152,Airport,TH,58835,Tue Apr 03 22:54:52 +0000 2012,420
....

我需要删除出现次数少于 100 次的场地 ID。

我尝试使用以下代码:

joined = joined[joined.groupby("venue_id").venue_id.transform(len) >= 100]

其灵感来自 ID 为 13446480 的问题的答案。

问题是它给了我以下错误:

AttributeError: 'DataFrameGroupBy' object has no attribute 'venue_id'

请记住,我是 Pandas 的新手,我想学习,所以如果你也能给出一些解释,我将不胜感激。

干杯,

丹

【问题讨论】:

  • print (df.index) 是什么?
  • @jezrael 我已经用你的第一个建议解决了这个问题
  • 高人,很高兴能帮上忙!

标签: python pandas


【解决方案1】:

似乎第一列是索引,所以请帮助reset_index。

所以需要:

joined = joined.reset_index()
joined = joined[joined.groupby("venue_id")['venue_id'].transform(len) >= 100]

如果第一列是索引并且不需要reset_index,也对我有用:

joined = joined[joined.groupby("venue_id").transform(len) >= 100]

如果不使用最新版本的 pandas (0.20.1),则有必要添加一些列:

joined = joined[joined.groupby(level="venue_id")['latitude'].transform(len) >= 100]

编辑1:

Faster 将size 用作len。

joined = joined[joined.groupby("venue_id")['latitude'].transform('size') >= 100]

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 2015-05-08
    • 2013-10-11
    • 1970-01-01
    相关资源
    最近更新 更多