如何检查 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 婆婆高寿祝福语大全简短