HapiDaze
HapiDaze

Reputation: 621

Get the nth row with Pandas query() method

Suppose we create a dataframe like this:

import pandas as pd

df_ex = pd.DataFrame(
    {'sales': [10001.35, 12305.22, 11217.89]},
    index=['2022-08-08 00:00:00-04:00', '2022-08-09 00:00:00-04:00', '2022-08-10 00:00:00-04:00']
)
df_ex.index.names = ['date']

Either of these Pandas queries could be used to extract the second row:

query_date = '2022-08-09 00:00:00-04:00'

# Generically reference the index
df_ex.query('index == @query_date')

# Or, explicitly reference the index by its name
df_ex.query('date == @query_date')

Now, suppose we start out only knowing the ordinal position of the required row. The following code does the job:

idx = 1
query_date = df_ex.iloc[idx].name

df_ex.query('date == @query_date')

However, I suspect line 2 is an unnecessary step.

Can anyone suggest a way of referencing the ordinal index position, with the idx value, directly in the body of the query string?

Upvotes: 0

Views: 399

Answers (1)

Nikolay Zakirov
Nikolay Zakirov

Reputation: 1584

Do you really need a query? You could just do this

df_ex.iloc[1:2]

(this way the df_ex is not being transformed to Series)

if you really need query here is a one liner in a fairly ugly way

df_ex.query("index == sales.head(2).tail(1).index.item()")

Upvotes: 2

Related Questions