- Pandas.DataFrame.query() by Examples
- 1. Quick Examples of pandas query()
- 3. Using DataFrame.query()
- 4. Select Rows Based on List of Column Values
- 5. Query with Multiple Conditions
- 6. Query Rows using apply()
- 8. Other Examples using df[] and loc[]
- Conclusion
- Related Articles
- References
- You may also like reading:
- Naveen (NNK)
- This Post Has One Comment
- Как выбрать строки по нескольким условиям, используя Pandas loc
- Метод 1: выберите строки, которые соответствуют нескольким условиям
- Способ 2: выберите строки, которые соответствуют одному из нескольких условий
- Дополнительные ресурсы
- Как фильтровать кадр данных Pandas по нескольким условиям
- Пример 1. Фильтрация по нескольким условиям с использованием оператора «И»
- Пример 2. Фильтрация по нескольким условиям с использованием оператора «ИЛИ»
- Пример 3. Фильтрация по нескольким условиям с использованием списка
Pandas.DataFrame.query() by Examples
Pandas DataFrame.query() method is used to query the rows based on the expression (single or multiple column conditions) provided and returns a new DataFrame. In case you wanted to update the existing referring DataFrame use inplace=True argument.
In this article, I will explain the syntax of the Pandas DataFrame query() method and several working examples like query with multiple conditions and query with string contains to new few.
- pandas.DataFrame.filter() – To filter rows by index and columns by name.
- pandas.DataFrame.loc[] – To select rows by indices label and column by name.
- pandas.DataFrame.iloc[] – To select rows by index and column by position.
- pandas.DataFrame.apply() – To custom select using lambda function.
1. Quick Examples of pandas query()
If you are in hurry, below are quick examples of how to use pandas.DataFrame.query() method.
= 23000") df.query("`Courses Fee` >= 23000 and `Courses Fee`
If you are a learner, Let’s see with sample data and run through these examples and explore the output to understand better. First, let’s create a pandas DataFrame from Dict.
df = pd.DataFrame(technologies) print(df)
Note that the above DataFrame also contains None and Nan values on Duration column that I would be using in my examples below to select rows that has None & Nan values or select ignoring these values.
3. Using DataFrame.query()
Following is the syntax of DataFrame.query() method.
- expr – expression takes conditions to query rows
- inplace – Defaults to False . When set to True , it updates the referring DataFrame and query() method returns None .
- **kwargs – Keyword arguments that works with eval()
DataFrame.query() takes condition in expression to select rows from a DataFrame. This expression can have one or multiple conditions.
In case you wanted to use a variable in the expression, use @ character .
If you notice the above examples return a new DataFrame after filtering the rows. if you wanted to update the existing DataFrame use inplace=True
If you wanted to select based on column value not equals then use != operator .
4. Select Rows Based on List of Column Values
If you have values in a python list and wanted to select the rows based on the list of values, use in operator , it’s like checking a value contains in a list of string values.
You can also write with a list of values in a python variable.
To select rows that are not in a list of column values can be done using not in operator .
If you have column names with special characters using column name surrounded by tick ` character .
5. Query with Multiple Conditions
In Pandas or any table-like structures, most of the time we would need to select the rows based on multiple conditions by using multiple columns, you can do that in Pandas DataFrame as below.
Yields below output. Alternatively, you can also use pandas loc with multiple conditions.
6. Query Rows using apply()
pandas.DataFrame.apply() method is used to apply the expression row-by-row and return the rows that matched the values. The below example returns every match when Courses contains a list of specified string values.
Yields below output. A lambda expression is used with pandas to apply the function for each row.
8. Other Examples using df[] and loc[]
= 1000) & (df['Discount'] = 1200) & (df['Fee'] >= 23000 )] # Select based on value contains print(df[df['Courses'].str.contains("Spark")]) # Select after converting values print(df[df['Courses'].str.lower().str.contains("spark")]) # Select startswith print(df[df['Courses'].str.startswith("P")])
Conclusion
In this article, I have explained multiple examples of how to query Pandas DataFrame Rows based on single and multiple conditions, from a list of values (checking column value exists in list of string values) e.t.c. Remember when you query DataFrame Rows, it always returns a new DataFrame with selected rows, in order to update existing df you have to use inplace=True . I hope this article helps you learn Pandas.
Related Articles
References
You may also like reading:
Naveen (NNK)
SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..
This Post Has One Comment
Hi there, I liked this article. One point…
Perhaps the implementation has changed, but I don’t think the pandas query likes spaces in the column names. I had a column named “Return Date” and I had to change it to “Return_Date” to avoid getting a key error.
Как выбрать строки по нескольким условиям, используя Pandas loc
Вы можете использовать следующие методы для выбора строк кадра данных pandas на основе нескольких условий:
Метод 1: выберите строки, которые соответствуют нескольким условиям
df.loc[((df['col1'] == 'A') &(df['col2' ] == 'G'))]
Способ 2: выберите строки, которые соответствуют одному из нескольких условий
В следующих примерах показано, как использовать каждый из этих методов на практике со следующими пандами DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team position assists rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 A F 9 6 4 B G 12 6 5 B G 9 5 6 B F 9 9 7 B F 4 12
Метод 1: выберите строки, которые соответствуют нескольким условиям
В следующем коде показано, как выбирать только строки в DataFrame, где команда равна «A», а позиция равна «G»:
#select rows where team is equal to 'A' and position is equal to 'G' df.loc[((df['team'] == 'A') &(df['position'] == 'G'))] team position assists rebounds 0 A G 5 11 1 A G 7 8
В DataFrame было только две строки, удовлетворяющие обоим этим условиям.
Способ 2: выберите строки, которые соответствуют одному из нескольких условий
В следующем коде показано, как выбрать только те строки в DataFrame, в которых число передач больше 10 или число подборов меньше 8:
#select rows where assists is greater than 10 or rebounds is less than 8 df.loc[((df['assists'] > 10) |(df['rebounds'] < 8))] team position assists rebounds 3 A F 9 6 4 B G 12 6 5 B G 9 5
В DataFrame было только три строки, удовлетворяющие обоим этим условиям.
Примечание. В этих двух примерах мы отфильтровали строки на основе двух условий, но с использованием & и | операторы, мы можем фильтровать столько условий, сколько захотим.
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:
Как фильтровать кадр данных Pandas по нескольким условиям
Часто вам может понадобиться отфильтровать кадр данных pandas по более чем одному условию. К счастью, это легко сделать с помощью логических операций.
В этом руководстве представлено несколько примеров того, как фильтровать следующие кадры данных pandas по нескольким условиям:
import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team points assists rebounds 0 A 25 5 11 1 A 12 7 8 2 B 15 7 10 3 B 14 9 6 4 C 19 12 6
Пример 1. Фильтрация по нескольким условиям с использованием оператора «И»
В следующем коде показано, как фильтровать DataFrame с помощью оператора and ( & ):
#return only rows where points is greater than 13 and assists is greater than 7 df[(df.points > 13) & (df.assists > 7)] team points assists rebounds 3 B 14 9 6 4 C 19 12 6 #return only rows where team is 'A' and points is greater than or equal to 15 df[(df.team == 'A') & (df.points >= 15)] team points assists rebounds 0 A 25 5 11
Пример 2. Фильтрация по нескольким условиям с использованием оператора «ИЛИ»
В следующем коде показано, как фильтровать DataFrame с помощью оператора или ( | ):
#return only rows where points is greater than 13 or assists is greater than 7 df[(df.points > 13) | (df.assists > 7)] team points assists rebounds 0 A 25 5 11 2 B 15 7 10 3 B 14 9 6 4 C 19 12 6 #return only rows where team is 'A' or points is greater than or equal to 15 df[(df.team == 'A') | (df.points >= 15)] team points assists rebounds 0 A 25 5 11 1 A 12 7 8 2 B 15 7 10 4 C 19 12 6
Пример 3. Фильтрация по нескольким условиям с использованием списка
В следующем коде показано, как фильтровать DataFrame, где значения строки находятся в некотором списке.
#define a list of values filter_list = [12, 14, 15] #return only rows where points is in the list of values df[df.points.isin (filter_list)] team points assists rebounds 1 A 12 7 8 2 B 15 7 10 3 B 14 9 6 #define another list of values filter_list2 = ['A', 'C'] #return only rows where team is in the list of values df[df.team.isin (filter_list2)] team points assists rebounds 0 A 25 5 11 1 A 12 7 8 4 C 19 12 6
Вы можете найти больше руководств по пандам здесь .