如何检查 Pandas 中是否存在某一列?
pandasserver side programmingprogramming更新于 2025/4/16 23:22:17
要检查 Pandas DataFrame 中是否存在某一列,我们可以采取以下步骤 −
步骤
创建一个二维、大小可变、可能异构的表格数据 df。
打印输入 DataFrame,df。
使用列名初始化 col 变量。
创建一个用户定义函数 check() 来检查 DataFrame 中是否存在某一列。
使用有效的列名调用 check() 方法。
使用无效列调用 check() 方法名称。
示例
import pandas as pd def check(col): if col in df: print "Column", col, "exists in the DataFrame." else: print "Column", col, "does not exist in the DataFrame." df = pd.DataFrame( { "x": [5, 2, 1, 9], "y": [4, 1, 5, 10], "z": [4, 1, 5, 0] } ) print "Input DataFrame is:
", df col = "x" check(col) col = "a" check(col)
输出
Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 Column x exists in the DataFrame. Column a does not exist in the DataFrame.