按N个属性

时间:2017-04-13 12:28:03

标签: python arrays group-by max namedtuple

我来自Java背景并且尽可能在我的工作环境中应用它来学习Python。我有一段功能正常的代码,我真的想改进它。

基本上我有一个带有3个数值和1个时间值的命名元组列表。

complete=[]
uniquecomplete=set()
screenedPartitions = namedtuple('screenedPartitions'['feedID','partition','date', 'screeeningMode'])

我解析了一个日志,在填充之后,我想创建一个简化集,该集基本上是最近日期成员,其中feedID,partition和screeningMode是相同的。到目前为止,我只能通过使用令人讨厌的嵌套循环来解决它。

for a in complete:
    max = a             
    for b in complete:
        if a.feedID == b.feedID and a.partition == b.partition and\
                       a.screeeningMode == b.screeeningMode and a.date < b.date:
            max = b
    uniqueComplete.add(max)

有人可以就如何改善这一点给我建议吗?用stdlib中的可用方法来解决这个问题会很棒,因为我想这里的主要任务是让我通过map / filter功能来思考它。

数据类似于

FeedID | Partition | Date           | ScreeningMode

68     |    5      |10/04/2017 12:40|   EPEP

164    |    1      |09/04/2017 19:53|   ISCION

164    |    1      |09/04/2017 20:50|   ISCION

180    |    1      |10/04/2017 06:11|   ISAN

128    |    1      |09/04/2017 21:16|   ESAN

所以 代码运行后,第2行将被删除,因为第3行是更新版本。

Tl;博士,这个SQL在Python中会是什么:

SELECT feedID,partition,screeeningMode,max(date)
from Complete
group by 'feedID','partition','screeeningMode'

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

import pandas as pd

df = pd.DataFrame(screenedPartitions, columns=screenedPartitions._fields)
df = df.groupby(['feedID','partition','screeeningMode']).max()

这实际上取决于您的日期的表示方式,但如果您提供数据我认为我们可以解决问题。