Home >Backend Development >Python Tutorial >How to Select Data from a pandas DataFrame Based on Multiple Complex Criteria?

How to Select Data from a pandas DataFrame Based on Multiple Complex Criteria?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 00:50:18141browse

How to Select Data from a pandas DataFrame Based on Multiple Complex Criteria?

Selecting with Complex Criteria from pandas.DataFrame

Consider the following DataFrame:

import pandas as pd
from random import randint

df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
                   'B': [randint(1, 9)*10 for x in range(10)],
                   'C': [randint(1, 9)*100 for x in range(10)]})

To select values from 'A' for which corresponding values for 'B' are greater than 50 and 'C' is not equal to 900, we can utilize Pandas' methods and idioms.

We begin by applying column operations to obtain Boolean Series objects:

df["B"] > 50
(df["B"] > 50) & (df["C"] != 900)

These Series represent the conditions we are interested in. We can then index into the DataFrame using these conditions to filter the data:

df["A"][(df["B"] > 50) & (df["C"] != 900)]

Alternatively, we can use .loc to achieve the same result:

df.loc[(df["B"] > 50) & (df["C"] != 900), "A"]

This method provides more control and allows for a more customizable indexing experience.

The resulting DataFrame will contain only the values of 'A' that satisfy the specified criteria.

The above is the detailed content of How to Select Data from a pandas DataFrame Based on Multiple Complex Criteria?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Weekend Tasks - ListNext article:Weekend Tasks - List