Home > Back-end >  Do mathematical operations with indexes in pandas
Do mathematical operations with indexes in pandas

Time:04-02

I am performing math operations on a dataframe. This is the operation that works for me.

df['delta'] = np.where (df ['peak'] == 1, df['value'] - df['value'].shift(1), np.NaN)

Now I want to do the EXACTLY same thing with index. Indexes are integers, but they have gaps.

My DataFrame looks like this:

, value, peak
40, 5878, 1
90, 8091, 1
98, 9091, 1
101,10987,1

So, how should I write my line? I mean something like this:

df['i'] = np.where (df ['peak'] == 1, df.index - df.index.shift(1), np.NaN)

So, I want to get column with values 50, 8, 3 and so on...

CodePudding user response:

Since df.index.shift() is only implemented for time-related indexes, use NumPy's diff as a replacement: np.diff(df.index, prepend=np.nan):

df['i'] = np.where(df.peak == 1, np.diff(df.index, prepend=np.nan), np.nan)
  • Related