HOWTO · Pandas

如何基於 Pandas DataFrame 中的列值刪除行

本教程介紹了使用諸如帶有 loc 的 drop 和布林掩碼之類的方法基於 Pandas DataFrame 中的列值刪除行。

本頁內容

我們將介紹通過使用 .drop(帶有和不帶有 loc)和布林掩碼檢查列值的條件來基於 DataFrame 刪除行的方法。

用 .drop 方法刪除 Pandas DataFrame 中列值的行

.drop 方法接受一個或一列列名,並刪除行或列。對於行,我們設定引數 axis=0,對於列,我們設定引數 axis=1(預設情況下,axis 為 0)。我們還可以得到 True 和 False 系列列值,根據應用於 Pandas DataFrame 中的條件。

示例程式碼:

# python 3.x
import pandas as pd

fruit_list = [
    ("Orange", 34, "Yes"),
    ("Mango", 24, "No"),
    ("banana", 14, "No"),
    ("Apple", 44, "Yes"),
    ("Pineapple", 64, "No"),
    ("Kiwi", 84, "Yes"),
]

# Create a DataFrame object
df = pd.DataFrame(fruit_list, columns=["Name", "Price", "Stock"])
# Get names of indexes for which column Stock has value No
indexNames = df[df["Stock"] == "No"].index
# Delete these row indexes from dataFrame
df.drop(indexNames, inplace=True)
print(df)

輸出:

     Name  Price Stock
0  Orange     34   Yes
3   Apple     44   Yes
5    Kiwi     84   Yes

我們也可以通過在 df.drop 方法中使用 .loc 來獲得類似的結果。

df.drop(df.loc[df["Stock"] == "Yes"].index, inplace=True)

我們還可以基於多個列值刪除行。在上面的示例中,我們可以刪除價格 >=30 和價格 <=70 的行。

示例程式碼:

# python 3.x
import pandas as pd

# List of Tuples
fruit_list = [
    ("Orange", 34, "Yes"),
    ("Mango", 24, "No"),
    ("banana", 14, "No"),
    ("Apple", 44, "Yes"),
    ("Pineapple", 64, "No"),
    ("Kiwi", 84, "Yes"),
]

# Create a DataFrame object
df = pd.DataFrame(fruit_list, columns=["Name", "Price", "Stock"])
indexNames = df[(df["Price"] >= 30) & (df["Price"] <= 70)].index
df.drop(indexNames, inplace=True)
print(df)

輸出:

     Name  Price Stock
1   Mango     24    No
2  banana     14    No
5    Kiwi     84   Yes

價格大於 30 且小於 70 的行已被刪除。

布林遮蔽方法刪除 Pandas DataFrame 中的行

布林遮蔽 boolean masking 是基於列值刪除 Pandas DataFrame 中的行的最好,最簡單的方法。

示例程式碼:

# python 3.x
import pandas as pd

# List of Tuples
fruit_list = [
    ("Orange", 34, "Yes"),
    ("Mango", 24, "No"),
    ("banana", 14, "No"),
    ("Apple", 44, "Yes"),
    ("Pineapple", 64, "No"),
    ("Kiwi", 84, "Yes"),
]

# Create a DataFrame object
df = pd.DataFrame(fruit_list, columns=["Name", "Price", "Stock"])
print(df[df.Price > 40])
print("............................")
print(df[(df.Price > 40) & (df.Stock == "Yes")])

輸出:

        Name  Price Stock
3      Apple     44   Yes
4  Pineapple     64    No
5       Kiwi     84   Yes
............................
    Name  Price Stock
3  Apple     44   Yes
5   Kiwi     84   Yes