如何检查 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 送给学长毕业祝福语简短