用 Python 编写一个程序来删除给定 DataFrame 中的一列或多列
假设你有一个数据框,
one two three0 1 2 3
1 4 5 6
删除单列的结果是,
two three0 2 3
1 5 6
在多列之后删除的结果是,
three0 3
1 6
为了解决这个问题,我们将按照下面给出的步骤 -
解决方案1
定义数据框
使用以下方法删除特定列,
del df['one']
例子
让我们看下面的代码以获得更好的理解 -
import pandas as pddata = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data,columns=('one','two','three'))
print("Before deletion\n", df)
del df['one']
print("After deletion\n", df)
输出
Before deletionone two three
0 1 2 3
1 4 5 6
After deletion
two three
0 2 3
1 5 6
解决方案2
定义数据框
使用 pop 函数删除特定列。它定义如下
df.pop('one')
例子
import pandas as pddata = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data,columns=('one','two','three'))
print("Before deletion\n", df)
df.pop('one')
print("After deletion\n", df)
输出
Before deletionone two three
0 1 2 3
1 4 5 6
After deletion
two three
0 2 3
1 5 6
解决方案3
定义数据框
应用以下方法删除多列,
df.drop(columns=['one','two'],inplace = True)
例子
import pandas as pddata = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data,columns=('one','two','three'))
print("Before deletion\n ", df)
df.drop(columns=['one','two'],inplace = True)
print("After deleting two columns\n", df)
输出
Before deletionone two three
0 1 2 3
1 4 5 6
After deletion
two three
0 2 3
1 5 6
After deleting two columns
three
0 3
1 6
以上是 用 Python 编写一个程序来删除给定 DataFrame 中的一列或多列 的全部内容, 来源链接: utcz.com/z/335645.html