Home > Blockchain >  How to get previous row of dataframe given index
How to get previous row of dataframe given index

Time:11-28

My goal is to get the previous element in a dataframe. My code below shows 30, which is the current one. How can show 20, the previous one of the current?

import pandas as pd
df1 = pd.DataFrame({'A':[10,20,30]}, index=['2021-11-24','2021-11-25','2021-11-26'])
df1['A']['2021-11-26']  # the current one

CodePudding user response:

Use Series.shift:

df1['A'].shift()['2021-11-26']
# 20

Or DataFrame.shift:

df1.shift()['A']['2021-11-26']
# 20

CodePudding user response:

You can

  • filter the df from beginning to the index value you have
  • take last
import pandas as pd

df = pd.DataFrame({'A': [10, 20, 30]},
                  index=['2021-11-24', '2021-11-25', '2021-11-26'])
before_idx = df.loc[df.index < '2021-11-26', 'A'].iloc[-1]
print(before_idx)

CodePudding user response:

Use shift and loc:

# fill_value=0 to avoid to get a float number
>>> df1.shift(fill_value=0).loc['2021-11-26', 'A']
20
  • Related