Python Pandas - 刪除 DataFrame 中的行



Pandas DataFrame 是一種二維資料結構,用於以表格格式排列資料,包含行和列。DataFrame 通常用於 Python 中的資料分析和處理任務,可以有效地處理大型資料集。資料預處理中的一個常見任務包括根據給定條件刪除包含不相關、缺失或特定值的多個或不需要的行。

在本教程中,我們將學習各種從 pandas DataFrame 中刪除/刪除多行的技術,例如使用.drop()方法、根據條件刪除行以及使用索引切片。

使用 drop() 方法刪除行

pandas 的DataFrame.drop()方法用於從 pandas DataFrame 中刪除特定行。它可以用於根據標籤或位置(基於整數的索引)刪除行,並返回一個刪除了所選行的新 DataFrame。

示例:根據索引值刪除 DataFrame 行

這是一個根據其索引值使用DataFrame.drop()方法從 DataFrame 物件刪除行的基本示例。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [4, 5, 6, 7, 8]})

# Display original DataFrame
print("Original DataFrame:")
print(df)

# Drop the row with index 5
result = df.drop(3)

# Display the result
print("\nAfter dropping the row at index 5:")
print(result)

以下是上述程式碼的輸出:

Original DataFrame:
   A  B
0  1  4
1  2  5
2  3  6
3  4  7
4  5  8

After dropping the row at index 5:
   A  B
0  1  4
1  2  5
2  3  6
4  5  8

注意:如果 DataFrame 的索引中找不到指定的行標籤或索引,此方法將引發KeyError。可以透過將 errors 引數從 raise 設定為 ignore 來抑制此錯誤。

示例:根據標籤刪除 DataFrame 行

與之前的示例類似,以下示例將使用DataFrame.drop()方法根據其行標籤從 DataFrame 中刪除多行。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [4, 5, 6, 7, 8],
'C': [9, 10, 11, 12, 13]}, index=['r1', 'r2', 'r3', 'r4', 'r5'])

# Display original DataFrame
print("Original DataFrame:")
print(df)

# Drop the rows by row-labels
result = df.drop(['r1', 'r3'])

# Display the result
print("\nAfter dropping the rows:")
print(result)

以下是上述程式碼的輸出:

Original DataFrame:
    A  B   C
r1  1  4   9
r2  2  5  10
r3  3  6  11
r4  4  7  12
r5  5  8  13

After dropping the row:
    A  B   C
r2  2  5  10
r4  4  7  12
r5  5  8  13

根據條件刪除行

也可以根據條件表示式刪除行,這意味著可以使用選擇括號[]內的條件來過濾行。此技術通常用於刪除滿足特定條件的行。

示例

此示例演示瞭如何根據[]中指定的條件語句從 Pandas DataFrame 中刪除一行或多行。在此示例中,行刪除基於 DataFrame 的列值。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [4, 5, 6, 7, 8],
'C': [90, 0, 11, 12, 13]}, index=['r1', 'r2', 'r3', 'r4', 'r5'])

# Display original DataFrame
print("Original DataFrame:")
print(df)

# Dropping rows where column 'C' contains 0
result = df[df["C"] != 0]

# Display the result
print("\nAfter dropping the row where 'C' has 0:")
print(result)

以下是上述程式碼的輸出:

Original DataFrame:
    A  B   C
r1  1  4  90
r2  2  5   0
r3  3  6  11
r4  4  7  12
r5  5  8  13

After dropping the row where 'C' has 0:
    A  B   C
r1  1  4  90
r3  3  6  11
r4  4  7  12
r5  5  8  13

使用索引切片刪除行

這是刪除或刪除行的另一種方法,使用索引切片。此技術根據其索引位置刪除一定範圍的行。

示例

此示例演示瞭如何使用索引切片從 DataFrame 中刪除單行或多行。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [4, 5, 6, 7, 8]})

# Display original DataFrame
print("Original DataFrame:")
print(df)

# Drop the row using the index slicing
result = df.drop(df.index[2:4])

# Display the result
print("\nAfter dropping the row at 2 and 3:")
print(result)

以下是上述程式碼的輸出:

Original DataFrame:
   A  B
0  1  4
1  2  5
2  3  6
3  4  7
4  5  8

After dropping the row at 2 and 3:
   A  B
0  1  4
1  2  5
4  5  8
廣告