Python Groupby语句 [英] Python Groupby statement

查看:52
本文介绍了Python Groupby语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将以下详细信息列表分组:

I mam trying to group the following details list:

details = [('20130325','B'), ('20130320','A'), ('20130325','B'), ('20130320','A')]

>>for k,v in itertools.groupby(details,key=operator.itemgetter(0)):
>>  print k,list(v)

这是上面的groupby语句的输出:

And this is the output with the above groupby statement:

20130325 [('20130325', 'B')]

20130320 [('20130320', 'A')]

20130325 [('20130325', 'B')]

20130320 [('20130320', 'A')]

但是我的预期输出是:

20130325 [('20130325', 'B'),('20130325', 'B')]

20130320 [('20130320', 'A'),('20130320', 'A')]

我在某处做错了吗?

推荐答案

您必须先对详细信息进行排序:

You have to sort your details first:

details.sort(key=operator.itemgetter(0))

fst = operator.itemgetter(0)
itertools.groupby(sorted(details, key=fst), key=fst)

 

Groupby将连续的匹配记录分组在一起.

Groupby groups consecutive matching records together.

文档:

groupby()的操作类似于Unix中的uniq过滤器.每当键函数的值更改时,它就会生成一个中断或新组(这就是为什么通常需要使用相同的键函数对数据进行排序的原因).这种行为与SQL的GROUP BY有所不同,后者的GROUP BY会聚合通用元素,而不管其输入顺序如何.

The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.

这篇关于Python Groupby语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆