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
Release: 2024-12-24 00:50:18
Original
135 people have browsed it

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)]})
Copy after login

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)
Copy after login

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)]
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template