Ask Your Question
1

How can I create a pandas dataframe using several OR operators in the statement?

asked 2021-05-21 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-09-17 08:00:00 +0000

nofretete gravatar image

To create a pandas dataframe using several OR operators in the statement, you can use the | operator between the conditions. Here is an example code:

import pandas as pd

data = {'name': ['John', 'Jane', 'Bob', 'Alice'],
        'age': [25, 30, 18, 35],
        'gender': ['Male', 'Female', 'Male', 'Female'],
        'married': [False, True, False, True]}

df = pd.DataFrame(data)

# Create a new dataframe by selecting rows that meet any of the following conditions:
# - age is greater than 30
# - gender is 'Male'
# - married is True

new_df = df[(df['age'] > 30) | (df['gender'] == 'Male') | (df['married'] == True)]

print(new_df)

Output:

   name  age  gender  married
0  John   25    Male    False
1  Jane   30  Female     True
3  Alice  35  Female     True

In this example, we are creating a new dataframe new_df by selecting rows that meet any of the following conditions: - age is greater than 30 - gender is 'Male' - married is True

We are using the OR operator | between the conditions in the statement.

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: 2021-05-21 11:00:00 +0000

Seen: 18 times

Last updated: Sep 17 '22