I have a DataFrame that I am grouping. I would like to add another column to the data frame, which is the result of the diff function for each group. Sort of:
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C' : np.random.randn(8), 'D' : np.random.randn(8)}) df_grouped = df.groupby('B') for name, group in df_grouped: new_df["D_diff"] = group["D"].diff()
I would like to get the difference of column D for each group and have DF that includes a new column with diff calculation.
source share