【发布时间】: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