Home > Backend Development > Python Tutorial > How to Select Data from a Pandas DataFrame Based on Multiple Conditions?

How to Select Data from a Pandas DataFrame Based on Multiple Conditions?

Linda Hamilton
Release: 2024-12-08 12:07:09
Original
629 people have browsed it

How to Select Data from a Pandas DataFrame Based on Multiple Conditions?

Selecting with Complex Criteria from Pandas.DataFrame

Pandas's DataFrame offers powerful methods and idioms for data manipulation. Here's an example of how to select values based on complex criteria:

Problem:

Consider a DataFrame with columns "A," "B," and "C". Select values from "A" for which corresponding values for "B" are greater than 50 and for "C" are not equal to 900.

Solution:

  1. Create the 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
  1. Create Boolean Series for Criteria:
b_criteria = df["B"] > 50
c_criteria = df["C"] != 900
Copy after login
  1. Combine Criteria Using Boolean Operators:
selection_criteria = b_criteria & c_criteria
Copy after login
  1. Use .loc to Select:
selected_rows = df.loc[selection_criteria, "A"]
Copy after login

Example:

print(selected_rows)
# Output:
# 2    5000
# 3    8000
# Name: A, dtype: int64
Copy after login

Note:

Using .loc ensures that modifications made to the selected data only affect a copy, preserving the original DataFrame's integrity.

The above is the detailed content of How to Select Data from a Pandas DataFrame Based on Multiple Conditions?. 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