如何在 Pandas DataFrame 行中搜索值?
在本文中,我们将了解如何在Python中搜索 Pandas DataFrame 行中的值。
导入库和数据
在这里,我们将导入所需的模块,然后将数据文件作为数据帧读取。
所用数据集的链接在这里
Python3
# importing pandas as ps
import pandas as pd
# importing data using .read_csv() method
df = pd.read_csv("data.csv")
Python3
df[df["Purchased"] == "Yes"]
# This line of code will print all rows
# which satisfy the condition df["Purchased"] == "Yes"
# In other words df["Purchased"] == "Yes"
# will return a boolean either true or false.
# if it returns true then we will print that
# row otherwise we will not print the row.
Python3
df[(df["Age"] >= 35) & (df["Age"] <= 40)]
# This line of code will return all
# rows which satisfies both the conditions
# ie value of age >= 35 and value of age <= 40
输出:
搜索值
在这里,我们将在数据框中搜索列名。
Syntax : df[df[‘column_name’] == value_you_are_looking_for]
where df is our dataFrame
我们将在购买列中搜索所有值为“是”的行。
Python3
df[df["Purchased"] == "Yes"]
# This line of code will print all rows
# which satisfy the condition df["Purchased"] == "Yes"
# In other words df["Purchased"] == "Yes"
# will return a boolean either true or false.
# if it returns true then we will print that
# row otherwise we will not print the row.
输出:
我们还可以使用多个条件来搜索一个值。让我们看一个示例来查找年龄值在 35 到 40 之间的所有行。
Syntax : df[condition]
where df is our dataFrame
Python3
df[(df["Age"] >= 35) & (df["Age"] <= 40)]
# This line of code will return all
# rows which satisfies both the conditions
# ie value of age >= 35 and value of age <= 40
输出: