如何检查 Pandas 中是否存在列?

要检查 Pandas DataFrame 中是否存在列,我们可以采取以下步骤 -

步骤

  • 创建二维、大小可变、潜在异构的表格数据df

  • 打印输入数据帧df

  • 使用列名初始化col变量。

  • 创建一个用户定义的函数check()来检查 DataFrame 中是否存在列。

  • check()使用有效的列名调用方法。

  • check()使用无效的列名调用方法。

示例

import pandas as pd

def check(col):
   if col in df:
      print "Column", col, "存在于 DataFrame 中。"
   else:
      print "Column", col, "DataFrame 中不存在。"

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)

print "Input DataFrame is:\n", 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 存在于 DataFrame 中。
Column a DataFrame 中不存在。