0

Given a datetime series, how do I get the int position? I am able to obtain datetime index right now, but I need int position index instead.

Sample Code

# range contains 5 rows of datetime indexed data
print(range) 

# get rows of data having value greater than 4
print(range[range.gt(4)].index)

This is the print out result

Date
2020-07-21 22:00:00    6.543779
2020-07-21 22:30:00    4.095121
2020-07-21 23:00:00    4.156970
2020-07-21 23:30:00    3.819589
2020-07-22 00:00:00    4.252539
Length: 5, dtype: float64

# This returned datetime index but int position is needed
DatetimeIndex(['2020-07-21 22:00:00', '2020-07-21 22:30:00',
               '2020-07-21 23:00:00', '2020-07-22 00:00:00'],
              dtype='datetime64[ns]', name='Date', length=4, freq=None)

Expecting result

# positions of data where values greater than 4
[0,1,2,4]

Solution

Quick answer, use .reset_index()

# Use reset_index() to assign int index to the series
range = range.reset_index()

# range[0] is the column with the value you want to compare
#   .gt(4) is to get all rows with value greater than 4
#   .index is to get the index of the filter rows
print(range[range[0].gt(4)].index)

This will print below result

Int64Index([0,1,2,4], dtype='int64', length=4)

1 Answer 1

1

You would want to reset the index and query back the index.

print(your_dataframe.reset_index().index)

Plus, to access the positional location, you can use your_dataframe.iloc[position].

Note: Beware that if you reset your index after you filter your data, the index will not be the same as the it is before the filtration. You need to reset your index before you do any filtration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.