从 Pandas DataFrame 中使用复杂的标准进行选择
我们可以使用不同的标准来比较PandasDataFrame的所有列值。我们可以执行df[col]<5,df[col]==10等比较操作。例如,如果我们使用条件df[col]>2,那么它将检查col中的所有值并比较是否它们大于2。对于所有列值,如果条件成立,它将返回True,否则返回False。让我们举一个例子,看看它是如何完成的。
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧df。
使用列名初始化变量col。
执行一些比较操作。
打印结果数据帧。
示例
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