how do i make a row with the first instance of the string?

Use DataFrameGroupBy.diff with replace first missing values by original by Series.fillna:

df['delta'] = df.groupby('person')['expenditure'].diff().fillna(df['expenditure'])
print (df)
  person  days  expenditure  delta
0      A     1           10   10.0
1      A     2           24   14.0
2      A    10           45   21.0
3      B     2            0    0.0
4      B     7            2    2.0
5      B     8           10    8.0
6      C     5           50   50.0
7      C     6           78   28.0
8      C     7           90   12.0

And for second is possible processing both columns and then divide in DataFrame.eval:

df['delta'] = (df.groupby('person')[['expenditure', 'days']].diff()
                 .fillna(df[['expenditure','days']])
                 .eval('expenditure / days'))

What working same like:

df['delta'] = (df.groupby('person')['expenditure'].diff().fillna(df['expenditure'])
                .div(df.groupby('person')['days'].diff().fillna(df['days'])))

print (df)
  person  days  expenditure   delta
0      A     1           10  10.000
1      A     2           24  14.000
2      A    10           45   2.625
3      B     2            0   0.000
4      B     7            2   0.400
5      B     8           10   8.000
6      C     5           50  10.000
7      C     6           78  28.000
8      C     7           90  12.000

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top