使用 Python 编写程序,删除给定 DataFrame 中的一列或多列。
假设你有一个 DataFrame:
one two three 0 1 2 3 1 4 5 6
删除单个列的结果为:
two three 0 2 3 1 5 6
删除多个列的结果为:
three 0 3 1 6
为了解决这个问题,我们将遵循以下步骤:
方案 1
定义一个 DataFrame
使用以下方法删除特定列:
del df['one']
示例
让我们看看下面的代码来更好地理解:
import pandas as pd data = [[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 deletion one two three 0 1 2 3 1 4 5 6 After deletion two three 0 2 3 1 5 6
方案 2
定义一个 DataFrame
使用 pop 函数删除特定列。定义如下:
df.pop('one')
示例
import pandas as pd data = [[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 deletion one two three 0 1 2 3 1 4 5 6 After deletion two three 0 2 3 1 5 6
方案 3
定义一个 DataFrame
应用以下方法删除多列:
df.drop(columns=['one','two'],inplace = True)
示例
import pandas as pd data = [[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 deletion one 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
广告