Ask Your Question
4

How can I search a pandas dataframe for the values in a specific column that meet multiple conditions on another column being True?

asked 2023-05-21 01:03:08 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-21 01:26:01 +0000

pufferfish gravatar image

To search a Pandas dataframe for values in a specific column that meet multiple conditions on another column being True, you can use the following code:

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'col1': ['A', 'B', 'C', 'D', 'E'],
                   'col2': [10, 20, 30, 40, 50],
                   'col3': [True, False, True, True, False]})

# search for values in col1 where col3 is True and col2 is greater than 20
result = df.loc[(df['col3'] == True) & (df['col2'] > 20), 'col1']

print(result)

Output:

2    C
3    D
Name: col1, dtype: object

In this example, we first create a sample dataframe with three columns. We then use the loc method to filter the dataframe by selecting rows where col3 is True and col2 is greater than 20. Finally, we select the values in col1 that meet both conditions. The resulting output is the values C and D in col1.

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-05-21 01:03:08 +0000

Seen: 11 times

Last updated: May 21 '23