Ask Your Question
2

How to identify the final elements in a Pandas dataframe that have a specific time interval between them?

asked 2021-12-07 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-04-30 00:00:00 +0000

lakamha gravatar image

To identify the final elements in a Pandas dataframe that have a specific time interval between them, you can follow these steps:

  1. Convert the index of your dataframe into a datetime index using pd.to_datetime.
df.index = pd.to_datetime(df.index)
  1. Use the diff method to calculate the time difference between rows.
time_diff = df.index.to_series().diff()
  1. Create a boolean mask to filter for rows that have the desired time interval.
mask = time_diff == pd.Timedelta("2 hours")
  1. Apply the mask to your dataframe to select the final elements that satisfy the condition.
final_elements = df[mask].tail()

This will select the final five elements that have a time difference of two hours between them. You can adjust the time interval and the number of final elements to your specific needs.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-07 11:00:00 +0000

Seen: 10 times

Last updated: Apr 30 '21