R Sta
R Sta

Reputation: 53

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

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?

Upvotes: 2

Views: 66

Answers (2)

jezrael
jezrael

Reputation: 863256

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()

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71610

You could use agg with np.diff:

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

Upvotes: 0

Related Questions