繁体   English   中英

Pandas:如何编写 groupby 加上可以按一列或多列分组的聚合?

[英]Pandas: how to write a groupby plus an aggregation that can group by one or many columns?

如何使用此 groupby 加聚合操作,使其可以灵活处理一个多个groupby 列?

# some data
df = pd.DataFrame({'col1': [1, 5, 1, 2, 2, 2], 'col2': [2, 2, 2, 3, 3, 3], 'col3': [999, 999, 999, 999, 999, 999],
                  'time': ['2020-01-25 12:24:33', '2020-01-25 14:24:33', '2020-01-25 18:24:33',
                           '2020-01-25 09:24:33', '2020-01-25 10:24:33', '2020-01-25 11:24:33']})

# convert time
df['time'] = pd.to_datetime(df['time'])

# groupby with one col, works
df.groupby(['col1', df['time'].dt.floor('d')]).tail(1)

# how to use this structure while being flexibly able to group by one or more cols?
two_cols = ['col1', 'col2']
df.groupby([two_cols, df['time'].dt.floor('d')]).tail(1)

两种操作的预期 output 相同:

    col1    col2    col3    time
    5   2   999 2020-01-25 14:24:33
    1   2   999 2020-01-25 18:24:33
    2   3   999 2020-01-25 11:24:33

Pandas 正在寻找groupby() function 的标签列表,因此我们需要确保给他们一个列表。 我相信这行得通。

df.groupby(two_cols + [df['time'].dt.floor('d')]).tail(1)

您可以看到我们在groupby()中的参数是我们的列表two_cols + 另一个列表(在[]中),其中仅包含df['time']...系列。 因此,我们将两个列表组合成一个新的列表对象,这就是groupby()将运行的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM