如何检查 Pandas 中是否存在列?
要检查PandasDataFrame中是否存在列,我们可以采取以下步骤-
步骤
创建二维、大小可变、潜在异构的表格数据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中不存在。
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短