How to include grouping variable in the groupby().diff() results

Viewed 57

Newby to pandas here so go easy on me.

I have a dataframe with lots of columns. I want to do something like

df.groupby('row').diff()

However, the result of the groupby don't include the row column.

How do I include the row column in the groupby results.

Alternatively, is it possible to merge the groupby results in the dataframe?

2 Answers

Create index by row column first:

df1 = df.set_index('row').groupby('row').diff().reset_index()

Or:

df1 = df.set_index('row').groupby(level=0).diff().reset_index()

You could use agg with np.diff:

df.groupby('row').agg(np.diff)
Related