Pandas教程-Pandas中删除列
在Pandas中,我们可能需要从Pandas DataFrame中删除列或一些行。通常情况下,如果不再需要进行进一步研究的列/行,则会删除这些列/行。有几种方法可以实现这一目标,但在Pandas中最好的方法是使用.drop()方法。DataFrame通常可能包含对研究无关的列。应该从DataFrame中删除这样的列,以便我们可以集中精力研究剩余的列。
列可以通过定义标签名称和相应的轴或简单指定索引或列名来省略。此外,可以通过使用多索引定义级别来删除各个级别上的标签。在本文中,我们将讨论使用一些示例删除pandas中的列。
drop()方法
drop()方法用于从行或列中删除一组标签。我们可以通过定义标签名称和匹配轴或直接定义索引或列名来省略行或列。可以通过定义级别来删除多索引上的标签。我们可以使用.drop()功能删除或删除python DataFrame的一个或多个列。
语法:
DataFrame.drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
参数:
- 标签: 列的标签或行索引值的字符串或列表。
- 索引: 提供行标签。
- 级别: 在多索引DataFrame的情况下,用于确定应从中删除标签的级别。它接受级别位置或级别名称作为输入。
- 轴: 指示应删除列还是行。要删除列,请将轴设置为1或'columns'。默认情况下,它会从DataFrame中删除行。
- 列: 这是axis = 'columns'的替代项。它接受单个列标签或列标签列表作为输入。
- Inplace: 它指定是返回新的DataFrame还是修改现有的DataFrame。它是一个默认值为False的布尔标志。
- 错误: 如果设置为'ignore',则忽略错误。
返回值
- 如果inplace = True,则返回具有删除列的DataFrame或None。
- 如果找不到标签,则引发KeyError。
删除单个列
DataFrame可能需要删除单个或多个列。
示例: 我们使用df.drop(columns='col name')来从下面的示例中删除DataFrame的'age'列。
import pandas as pd
student_dict = {"name": ["Joe", "Nat"], "age": [20, 21], "marks": [85.10, 77.80]}
# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print(student_df)
# drop column
student_df = student_df.drop(columns='age')
print(student_df)
输出: 执行此代码后,我们将获得以下输出:
name age marks
0 Joe 20 85.1
1 Nat 21 77.8
name marks
0 Joe 85.1
1 Nat 77.8
使用axis='column'或axis=1的drop函数
要删除列,请在DataFrame.drop()方法的轴参数中使用axis。可以使用行或列作为轴。列轴由数字1或'columns'表示。设置axis = 1或axis = 'columns',并使用要删除的列名列表。
示例: 让我们以上面的示例来理解如何使用axis = 'column'和axis = 1的drop函数。
student_df = student_df.drop(['age', 'marks'], axis='columns')
# alternative both generates same result
student_df = student_df.drop(['age', 'marks'], axis=1)
输出: 执行此代码后,我们将获得以下输出:
name age marks
0 Joe 20 85.1
1 Nat 21 77.8
name
0 Joe
1 Nat
删除多个列
有两个DataFrame.drop()方法参数,我们可以同时删除DataFrame中的多个列。
- 使用column参数指定要删除的列名列表。
- 将轴设置为1,并移动列名列表。
示例: 让我们以一个示例来了解如何一次删除多列。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [24, 18], "marks": [77.29, 69.15]}
student_df = pd.DataFrame(student_dict)
print(student_df.columns.values)
# drop 2 columns at a time
student_df = student_df.drop(columns=['age', 'marks'])
print(student_df.columns.values)
输出: 执行此代码后,我们将获得以下输出:
name age marks
0 John 24 77.29
1 Alex 18 69.15
name
0 John
1 Alex
原地删除列
在先前的示例中,每当执行删除操作时,Pandas都会生成DataFrame的新副本,因为修改不是在原地进行的。通过inplace参数指定是否从现有DataFrame中删除列或创建其副本。
- 如果inplace = True,则在不返回任何内容的情况下更新当前DataFrame。
- 如果将inplace参数设置为False,则生成具有更新更改的新DataFrame并返回它。
示例: 让我们解释一下如何使用drop函数原地删除列。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [24, 18], "marks": [79.18, 68.79]}
student_df = pd.DataFrame(student_dict)
print(student_df.columns.values)
# drop columns in place
student_df.drop(columns=['age', 'marks'], inplace=True)
print(student_df.columns.values)
输出: 执行上述代码后,我们将获得以下输出:
name age marks
0 John 24 79.18
1 Alex 18 68.79
name
0 John
1 Alex
通过抑制错误删除列
如果要删除的列在数据集中不存在,则DataFrame.drop()方法会引发KeyError。如果我们只想删除列(如果存在),则可以使用errors参数删除错误。
- 将errors='ignore'设置为忽略任何错误。
- 将errors='raised'设置为为未知列生成KeyError。
示例: 让我们通过抑制错误来删除列。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [24, 18], "marks": [79.49, 82.54]}
# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print(student_df)
# supress error
student_df = student_df.drop(columns='salary', errors='ignore') # No change in the student_df
# raise error
student_df = student_df.drop(columns='salary') # KeyError: "['salary'] not found in axis"
输出: 执行上述代码后,我们将获得以下输出:
name age marks
0 John 24 79.49
1 Alex 18 82.54
raise KeyError(f"{labels[mask]} not found in axis")
KeyError: "['salary'] not found in axis"
通过索引位置删除列
如果我们要从DataFrame中删除列但不知道它们的名称,我们可以通过使用索引位置删除该列。列索引从0(零)开始,直到最后一列的索引值为len(df.columns)-1。
删除前n列
如果需要从DataFrame中删除前'n'列,我们可以使用DataFrame.iloc和Python的range()函数来定义要删除的列的范围。在DataFrame.drop()的column参数中,我们需要使用内置函数range()。
示例: 让我们以一个示例来了解如何删除DataFrame中的前n列。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [24, 18], "marks": [
84.45, 76.11], "class": ["A", "B"],
"city": ["US", "UK"]}
# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print(student_df.columns.values)
# drop column 1 and 2
student_df = student_df.drop(columns=student_df.iloc[:, range(2)])
# print only columns
print(student_df.columns.values)
输出: 执行上述代码后,我们将获得以下输出:
name age marks class city
0 John 24 84.45 A US
1 Alex 18 76.11 B UK
marks class city
84.45 A US
76.11 B UK
删除最后一列
假设我们想要排除DataFrame的第一列或最后一列而不使用列名。使用DataFrame.columns属性来删除一个DataFrame列,根据其索引位置简单地将df.columns[index]移动到DataFrame.drop的columns parameter()。
示例: 让我们以一个示例来了解如何从DataFrame中删除最后一列。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [24, 18], "marks": [68.44, 85.67]}
# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print(student_df.columns.values)
# find position of the last column and drop
pos = len(student_df.columns) - 1
student_df = student_df.drop(columns=student_df.columns[pos])
print(student_df.columns.values)
# delete column present at index 1
# student_df.drop(columns = student_df.columns[1])
输出: 执行上述代码后,我们将获得以下输出:
name age marks
0 John 24 68.44
1 Alex 18 85.67
name age
0 John 24
1 Alex 18
使用iloc删除列的范围
我们可能需要从数据集中删除第四列或整个一组列。我们可以使用DataFrame.iloc从DataFrame中选择一个或多个列。我们可以在列的参数中使用DataFrame.iloc来定义要删除的列的索引位置。
示例: 让我们以一个示例来了解如何使用iloc函数删除列的范围。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [24, 18], "marks": [79.64, 86.84]}
# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print(student_df.columns.values)
# drop column from 1 to 3
student_df = student_df.drop(columns=student_df.iloc[:, 1:3])
print(student_df.columns.values)
输出: 执行上述代码后,我们将获得以下输出:
name age marks
0 John 24 79.64
1 Alex 18 86.84
name
0 John
1 Alex
从多索引DataFrame中删除列
具有多个列头的DataFrame称为多索引DataFrame。这样的标题分为级别,级别0是第一个级别,级别1是第二个级别等。可以从多索引DataFrame的任何阶段删除列。默认情况下,它删除所有级别的列,但我们可以使用级别参数仅从一个级别中删除列。我们需要将级别名称作为level=level index传递。
示例: 让我们以一个示例来了解如何从多索引DataFrame中删除列。
import pandas as pd
# create column header
col = pd.MultiIndex.from_arrays([['Class X', 'Class Y', 'Class Z', 'Class Y'],
['Name', 'Marks', 'Name', 'Marks']])
# create DataFrame from 2darray
student_df = pd.DataFrame([['John', '87.22', 'Nat', '68.79'], ['Peter', '73.45', 'Alex', '82.76']], columns=col)
print(student_df)
# drop column
student_df = student_df.drop(columns=['Marks'], level=1)
print(student_df)
输出: 执行上述代码后,我们将获得以下输出:
Class X Class Y Class Z Class Y
Name Marks Name Marks
0 John 87.22 Nat 68.79
1 Peter 73.45 Alex 82.76
Class X Class Z
Name Name
0 John Nat
1 Peter Alex
使用函数删除列
我们还可以使用功能基于一些逻辑或条件删除列。我们可以使用内置和用户定义的函数来删除列。
使用pandas DataFrame.pop()函数删除列
如果我们只想删除一列,我们可以使用DataFrame.pop(col label)函数。我们需要传递要删除的列标签。通过在现有DataFrame中更新,它在原地删除列。如果未找到列,则会引发KeyError。
示例: 让我们以一个示例来了解如何使用pandas DataFrame.pop()函数删除列。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [24, 18], "marks": [62.46, 54.21]}
# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print(student_df)
# drop column
student_df.pop('age')
print(student_df)
输出: 执行上述代码后,我们将获得以下输出:
name age marks
0 John 24 62.46
1 Alex 18 54.21
name marks
0 John 62.46
1 Alex 54.21
使用loc函数删除列
如果我们想从DataFrame中快速轻松地删除所有列,我们可以使用DataFrame.loc在DataFrame.drop()的column参数中定义列标签。使用DataFrame.loc定义要删除的列标签。如果未定义列标签,例如df.loc[:],则DataFrame将删除所有列。
示例: 让我们以一个示例来了解如何使用loc函数删除列。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [25, 19], "marks": [79.68, 84.45]}
# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print(student_df.columns.values)
# drop column 1 and 2
student_df = student_df.drop(columns=student_df.loc[:])
# print only columns
print(student_df.columns.values)
输出: 执行上述代码后,我们将获得以下输出:
name age marks
0 John 24 79.68
1 Alex 18 84.45
使用pandas DataFrame删除函数
要从DataFrame中删除单个列,我们可以使用pandas内置函数del。这是从DataFrame中删除列的一个非常简化的方法。我们必须选择要从DataFrame中删除的DataFrame列并将其传递为del df[col label]。
示例: 让我们以一个示例来了解如何使用pandas DataFrame删除函数。
import pandas as pd
student_dict = {"name": ["John", "Alex"], "age": [23, 22], "marks": [57.88, 78.84]}
# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print(student_df)
# drop column
del student_df['age']
print(student_df)
输出: 执行上述代码后,我们将获得以下输出:
name age marks
0 John 23 57.88
1 Alex 22 78.84
name marks
0 John 57.88
1 Alex 78.84