如何在 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)输出
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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP