在 Pandas DataFrame 中按索引删除列
DataFrame 可以非常大,可以包含数百行和数百列。熟练掌握 DataFrame 的基本维护操作是很有必要的,比如删除其中的多列。我们可以使用 dataframe.drop()
方法,根据指定的 axis
从 DataFrame 中删除列或行,0 代表行,1 代表列。它根据一些标签来确定要删除的元素。例如,我们将从下面的 DataFrame 中删除列'a'
。
import pandas as pd
df = pd.DataFrame(
[[10, 6, 7, 8], [1, 9, 12, 14], [5, 8, 10, 6]], columns=["a", "b", "c", "d"]
)
print(df)
df.drop(["a"], axis=1, inplace=True)
print(df)
输出:
a b c d
0 10 6 7 8
1 1 9 12 14
2 5 8 10 6
b c d
0 6 7 8
1 9 12 14
2 8 10 6
请注意 drop 函数中 inplace
参数的使用。当 inplace
参数设置为 True
时,列将从原始 DataFrame 中删除;否则,将返回原始 DataFrame 的副本。
在我们的例子中,我们已经删除了列'a'
,但我们需要将其标签名传递给 dataframe.drop()
函数。在处理大型数据集时,我们应该同时处理许多列的此类任务,并且使用列索引代替它们的名称。
我们可以通过使用 dataframe.columns()
方法来实现,该方法返回 DataFrame 的所有列,并使用它们的索引将所需的列标签传递给 dataframe.drop()
函数。下面的代码片段解释了我们如何做到这一点。
import pandas as pd
df = pd.DataFrame(
[[10, 6, 7, 8], [1, 9, 12, 14], [5, 8, 10, 6]], columns=["a", "b", "c", "d"]
)
df.drop(df.columns[[1, 2]], axis=1, inplace=True)
print(df)
输出:
a d
0 10 8
1 1 14
2 5 6
它将删除索引为 1
或 2
的列。
我们也可以避免使用 axis
参数,只需在 dataframe.drop()
函数中提到 columns
参数,它就会自动指示要删除的列。例子
import pandas as pd
df = pd.DataFrame(
[[10, 6, 7, 8], [1, 9, 12, 14], [5, 8, 10, 6]], columns=["a", "b", "c", "d"]
)
df.drop(columns=df.columns[[1, 2]], inplace=True)
print(df)
输出:
a d
0 10 8
1 1 14
2 5 6
相关文章
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 系列日期时间转换为字符串