當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas DataFrame drop方法用法及代碼示例

Pandas 的 DataFrame.drop(~) 方法返回刪除了指定列/行的 DataFrame。

參數

1.labels | stringlist<string> | optional

要刪除的索引或列的名稱。

2. axis | intstring | optional

是否刪除列或行:

意義

0"index"

刪除行

1"columns"

刪除列

默認情況下,axis=0

3. index | stringlist<string> | optional

要刪除的索引的名稱。這相當於指定參數 axis=0labels

4. columns | stringlist<string> | optional

您要刪除的列的名稱。這相當於指定參數 axis=1labels

5. inplace | boolean | optional

  • 如果是True,那麽該方法將直接修改源DataFrame,而不是創建新的DataFrame。

  • 如果是False,則將創建並返回一個新的DataFrame。

默認情況下,inplace=False

注意

為了清楚起見,指定參數 indexcolumns,而不是指定 labelsaxis - 代碼更短、更清晰。

返回值

刪除了指定列/行的 DataFrame。如果 inplace=True ,則返回類型為 None,因為源 DataFrame 被直接修改。

例子

刪除列

考慮以下 DataFrame :

df = pd.DataFrame({"A":[1,2], "B":[3,4], "C":[5,6]})
df



   A  B  C
0  1  3  5
1  2  4  6
刪除單列

僅刪除A列:

df.drop(columns="A")



   B  C
0  3  5
1  4  6

這相當於以下代碼:

df.drop(labels="A", axis=1)   # This is not the preferred way since the intention is unclear.

請注意,從 inplace=False 開始,原始的 df 保持不變。

刪除多列

要刪除列 AB

df.drop(columns=["A","B"])



   C
0  5
1  6

這相當於以下代碼:

df.drop(labels=["A","B"], axis=1)    # This is not the preferred way since the intention is unclear.



   C
0  5
1  6

刪除行

考慮以下 DataFrame :

df = pd.DataFrame({"A":[1,2,3], "B":[4,5,6], "C":[7,8,9]})
df



   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9
刪除單行

要刪除第二行(即帶有 index=1 的行):

df.drop(index=1)



   A  B  C
0  1  4  7
2  3  6  9

這相當於以下代碼:

df.drop(labels=[1], axis=0)      # This is not the preferred way.



   A  B  C
0  1  4  7
2  3  6  9
刪除多行

要刪除前兩行(即帶有 index=0index=1 的行):

df.drop(index=[0, 1])



   A  B  C
2  3  6  9

這相當於以下代碼:

df.drop(labels=[0,1], axis=0)    # This is not the preferred way.



   A  B  C
2  3  6  9

原地掉落

要就地刪除行或列,我們需要設置 inplace=True 。其作用是,drop(~) 方法將直接修改源 DataFrame,而不是創建並返回新的 DataFrame。

作為示例,請考慮以下 DataFrame:

df = pd.DataFrame({"A":[1,2], "B":[3,4], "C":[5,6]})
df



   A  B  C
0  1  3  5
1  2  4  6

然後我們用 inplace=True 刪除列 AB

df.drop(columns=["A", "B"], inplace=True)
df



   C
0  5
1  6

如輸出所示,源 DataFrame 已被修改。

相關用法


注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | drop method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。