How to slice Python Pandas groupby objects with various lengths?

  pandas, pandas-groupby, python-3.x, slice

Creating the dataframe:

df = pd.DataFrame({'Set': [1, 1, 1, 2, 2, 2, 2, 2], 'Value': [1, 2, 3, 1, 2, 3, 4, 5]})

results in the DataFrame as shown below.

Pandas Dataframe

Next I perform a groupby operation by Set, and the first group is shown below.

grouped_by_Set = df.groupby('Set')
grouped_by_Set.get_group(1)

enter image description here

Now I want to select all but the last entry in the Value column per group. I can select the first three (for example) and last entry per group using grouped_by_Set.nth([0, 1, 2]) and grouped_by_Set.nth(-1), however selecting all but the last entry per group does not work with grouped_by_Set.nth(0:-1). I cannot specify the entries explicitly as the groups have different lengths.

Source: Python-3x Questions

LEAVE A COMMENT