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


为了检查 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)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

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.

更新于: 2021 年 8 月 30 日

9000+ 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始
广告