pythonpandas

How do I get the integer key (position) from first_valid_index()?


I have a pandas dataframe with an index as a date string like so: '2015-07-15', and another column along side it with a value associated with the dates.

To find out when the column first equals 5, I use this:

df[df['Column'] == 5].first_valid_index()

It gives me back

'2020-12-19'

Instead I want to know the integer index number of this occurence rather than the Date index so I can use the .iloc method to specify this index. How would I do so?


Solution

  • You need to reset_index before so that you can get your integer index.

    df.reset_index(inplace=True)
    df[df['Column'] == 5].first_valid_index()
    

    Alternate way without resetting index would be using get_loc. Assuming your data atleast contain 1 value

    df.index.get_loc(df.index[df['Column'] == 5][0])
    

    Combination of both would look like,

    df.index.get_loc(df[df['Column'] == 5].first_valid_index())