按熊猫分组

时间:2019-02-14 18:44:17

标签: python python-3.x pandas pandas-groupby

这是我的数据:

{'SystemID': {0: '95EE8B57',
 1: '5F891F03',
 2: '5F891F03',
 3: '5F891F03'},
 'Day': {0: '06/08/2018', 1: '05/08/2018', 2: '04/08/2018',   3: '05/08/2018'},
 'AlarmClass-S': {0: 4, 1: 2, 2: 4, 3: 0},
 'AlarmClass-ELM': {0: 0, 1: 0, 2: 0, 3: 2}}

我想执行聚合和过滤,在SQL中将其表示为

SELECT SystemID, COUNT(*) as count FROM table GROUP BY SystemID HAVING COUNT(*) > 2

结果应为

    {'SystemID': {0: '5F891F03'},
 'count': {0: '3'}}

如何在熊猫中做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用groupbycount,然后在末尾进行过滤。

(df.groupby('SystemID', as_index=False)['SystemID']
   .agg({'count': 'count'})
   .query('count > 2'))

   SystemID  count
0  5F891F03      3

(df.groupby('SystemID', as_index=False)['SystemID']
   .agg({'count': 'count'})
   .query('count > 2')
   .to_dict())
# {'SystemID': {0: '5F891F03'}, 'count': {0: 3}}