简体   繁体   English

使用 Pandas query() 方法获取第 n 行

[英]Get the nth row with Pandas query() method

Suppose we create a dataframe like this:假设我们像这样创建一个 dataframe:

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:这些 Pandas 查询中的任何一个都可用于提取第二行:

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.现在,假设我们一开始只知道所需行的序号 position。 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.但是,我怀疑第 2 行是不必要的步骤。

Can anyone suggest a way of referencing the ordinal index position, with the idx value, directly in the body of the query string?谁能建议一种直接在查询字符串正文中引用序号索引 position 和 idx 值的方法?

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) (这样 df_ex 不会被转换为系列)

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()")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM