Ask Your Question
4

How to use an OR statement to select/slice data from a pandas dataframe based on multiple conditions?

asked 2023-02-02 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-08-04 17:00:00 +0000

devzero gravatar image

To select/slice data from a pandas dataframe based on multiple conditions using OR statement, use the "|" (vertical bar) operator between the conditions inside the parentheses. Here's an example:

import pandas as pd

# creating a sample dataframe
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie', 'David'],
                   'age': [25, 30, 35, 40],
                   'gender': ['F', 'M', 'M', 'M'],
                   'salary': [50000, 60000, 70000, 80000]})

# selecting data based on multiple conditions using OR statement
selected_data = df[(df['gender'] == 'F') | (df['age'] > 35)]
print(selected_data)

In the example above, we used the OR statement "|" to select the rows where the gender is "F" OR the age is greater than 35. The resulting dataframe will have the rows where either of the conditions is true.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-02 11:00:00 +0000

Seen: 2 times

Last updated: Aug 04 '21