检查 pandas 中是否存在列
本教程演示了检查 python 中是否存在 pandas dataframe 中的列的方法。我们将在 python 中使用可用于执行此操作的 in
和 not in
运算符。
使用 in
运算符检查 pandas 中是否存在列
dataframe 是一种保存二维数据及其相应标签的排列。我们可以使用 dataframe.column
属性找到列标签。
为了确保列是否存在,我们使用 in
表达式。但是,在开始之前,我们需要在 pandas 中形成一个虚拟 dataframe 以使用上述技术。
在这里,我们创建了一个学生表现的 dataframe,列名称为 name
、promoted
和 marks
。
import pandas as pd
import numpy as np
# creating dataframe
df = pd.dataframe()
# adding columns to the dataframe
df["name"] = ["john", "doe", "bill"]
df["promoted"] = [true, false, true]
df["marks"] = [82, 38, 63]
# getting the dataframe as an output
print(df)
代码给出以下输出。
name promoted marks
0 john true 82
1 doe false 38
2 bill true 63
dataframe 准备好后,我们可以通过编写下面给出的代码来检查 dataframe 是否包含项目或为空。为此,我们可以使用两种方法。
我们可以使用 pandas 中存在的 df.empty
函数,或者我们可以使用 len(df.index)
检查 dataframe 的长度。
我们在下面的示例中使用了 pandas 属性 df.empty
。
if df.empty:
print("dataframe is empty!")
else:
print("not empty!")
由于我们已将数据插入列中,因此输出必须为 not empty!
。
not empty!
现在,让我们继续使用 in
方法检查 pandas dataframe 中的列是否存在。请参阅下面的代码以查看此功能的运行情况。
if "promoted" in df:
print("yes, it does exist.")
else:
print("no, it does not exist.")
代码给出以下输出。
yes, it does exist.
为了更清楚起见,也可以将其写成 if 'promoted' in df.columns:
,而不是仅仅写成 df
。
使用 not in
运算符检查 pandas 中是否存在列
让我们看看如何使用 not in
属性来执行相同的操作。它以相反的方式运行,并且由于属性中添加了否定,输出被反转。
这是下面给出的 not in
属性的示例工作。
if "promoted" not in df.columns:
print("yes, it does not exist.")
else:
print("no, it does exist.")
代码给出以下输出。
no, it does exist.
我们已经看到如何对 dataframe 中的单个列执行此操作。pandas 还使用户能够检查 dataframe 中的多个列。
这有助于快速完成任务并有助于同时对多个列进行分类。
下面是检查 pandas dataframe 中多列的代码片段。
if set(["name", "promoted"]).issubset(df.columns):
print("yes, all of them exist.")
else:
print("no")
代码给出以下输出。
yes, all of them exist.
set([])
也可以使用花括号来构造。
if not {"name", "promoted"}.issubset(df.columns):
print("yes")
else:
print("no")
输出将是:
no
这些是检查数据中的一列或多列的可能方法。同样,我们也可以对现成的数据而不是虚拟数据执行这些功能。
我们只需要通过 read_csv
方法使用 python pandas 模块导入 csv 文件。如果使用 google colab,请从 google.colab
导入 files
模块,以便在运行时从个人系统上传数据文件。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串