【问题标题】:How to iterate over pairs: a group and its next group?如何迭代对:一个组及其下一个组?
【发布时间】:2022-08-17 01:08:09
【问题描述】:

我有一个分组数据框:

df = pd.DataFrame({\'a\': [0, 0, 1, 1], \'b\': range(4)})
g = df.groupby(\'a\')

我想做一个需要每个组和下一个组的计算(当然最后一组除外).

如果它们是列表而不是组,这将很容易:

for x, x_next in zip(lst[], lst[1:]):
    ...

但不幸的是,选择切片不适用于pd.DataFrameGroupBy 对象:

g[1:]       # TypeError: unhashable type: \'slice\'. (It thinks I want to access the column by its name.)
g.iloc[1:]  # AttributeError: \'DataFrameGroupBy\' object has no attribute \'iloc\'

This question 是相关的,但它没有回答我的问题。

我自己发布了一个答案,但也许有更好或更有效的解决方案(也许是 pandas-native?).

    标签: python pandas group-by iteration


    【解决方案1】:

    您可以将pd.DataFrameGroupBy 转换为包含所有组的列表(在元组中:分组值和组), 然后遍历这个列表:

    lst = list(g)
    for current, next_one in zip(lst[], lst[1:]):
        ...
    

    或者,创建一个迭代器,并跳过它的第一个值:

    it = iter(g)
    next(it)
    for current, next_one in zip(g, it):
        ...
    

    更复杂的方法:

    g.groups 返回一个字典,其中键是分组列的唯一值,值是 团体。然后你可以尝试iterate over a dictionary,但我认为这会不必要地复杂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2015-11-05
      相关资源
      最近更新 更多