Home > Software design >  Extracting the previous value related to a given index
Extracting the previous value related to a given index

Time:12-15

I have extracted the indexes of pandas dataframe into a list based on specific criteria.

x = df.loc[df['Violation_Diff'] == 1].index.tolist()

Then I extracted the values related to those indexes from the dataframe into a series.

I only want the values of column 4 of the dataframe, so I used the below code.

Timestamp = df.iloc[x, 4]

But what I actually want is not the exact index values but the previous values of each of the given indexes (index - 1).

For example if my index list x = [2, 42] I want to extract the values related to index [1, 41] from the 4th column of the dataframe.

How can I do this in pandas?

CodePudding user response:

You can just update the index as shown below:

x = df.loc[df['Violation_Diff'] == 1].index.tolist()
x = [y-1 for y in x]

# x is now: [1,41]

Timestamp = df.iloc[x, 4]
  • Related