To give multiple conditions in the loc()
function in Pandas, you can use the &
(and) or |
(or) operator to combine multiple conditions.
This allows you to select rows from a dataframe that meet multiple criteria, rather than just one criterion.
Here's an example of using the loc()
function with multiple conditions in Pandas:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3, 4, 5],
"B": [6, 7, 8, 9, 10]})
# select rows where column A is greater than 2 and column B is less than 9
df_selected = df.loc[(df["A"] > 2) & (df["B"] < 9)]
# display the result
print(df_selected)
This will select rows from the dataframe where the value in column A
is greater than 2 and the value in column B
is less than 9. The &
operator is used to combine the two conditions, so that only rows that meet both conditions will be selected.
The output will be:
A B
2 3 8
You can also use the |
(or) operator to combine multiple conditions in the loc()
function. For example:
# select rows where column A is greater than 2 or column B is less than 9
df_selected = df.loc[(df["A"] > 2) | (df["B"] < 9)]
# display the result
print(df_selected)
A B
0 1 6
1 2 7
2 3 8
3 4 9
4 5 10
This will select rows from the dataframe where the value in column A
is greater than 2 or the value in column B
is less than 9.
Related tutorials curated for you
How to use pandas map() function
How to get the number of columns in a Pandas DataFrame
How to split a Pandas DataFrame by a column value
How to filter a Pandas DataFrame
How to GroupBy Index in Pandas
How to reorder columns in Pandas
How to drop duplicate columns in Pandas
How to join two DataFrames in Pandas
How to read a TSV file in Pandas
What is date_range() in Pandas?
How to apply a function to multiple columns in Pandas
What is idxmax() in Pandas?