使用复杂条件从 Pandas DataFrame 中进行选择
pythonserver side programmingprogramming更新于 2025/10/27 17:16:17
我们可以使用不同的条件来比较 Pandas DataFrame 的所有列值。我们可以执行比较操作,如 df[col]<5、df[col]==10 等。例如,如果我们使用条件 df[col]>2,那么它将检查 col 中的所有值并比较它们是否大于 2。对于所有列值,如果条件成立,它将返回 True,否则返回 False。让我们举个例子,看看它是如何完成的。
步骤
- 创建一个二维、大小可变、可能异构的表格数据,df。
- 打印输入 DataFrame,df。
- 用列名初始化变量 col。
- 执行一些比较操作。
- 打印结果 DataFrame。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print "Input DataFrame is:\n", df
col = "x"
print "Elements > 5 in column ", col, ":\n", df[col] > 5
print "Elements == 5 in column ", col, ":\n", df[col] == 5
col = "y"
print "Elements < 5 in column ", col, ":\n", df[col] < 5
print "Elements != 5 in column ", col, ":\n", df[col] != 5
输出
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Elements > 5 in column x : 0 False 1 False 2 True 3 False Name: x, dtype: bool Elements == 5 in column x : 0 True 1 False 2 False 3 False Name: x, dtype: bool Elements < 5 in column y : 0 True 1 False 2 False 3 True Name: y, dtype: bool Elements != 5 in column y : 0 True 1 True 2 False 3 True Name: y, dtype: bool
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

