在 Pandas 中獲取列與特定值匹配的行的索引

  1. 在 Pandas 中獲取包含整數/浮點數的行的索引
  2. 在 Pandas 中獲取包含字串的行的索引
在 Pandas 中獲取列與特定值匹配的行的索引

本文演示了 Pandas 中如何獲取符合特定條件的行的索引。

在特徵工程中,查詢行的索引的必要性是很重要的。這些技能對於去除 Dataframe 中的離群值或異常值很有用。索引,也就是行標籤,可以在 Pandas 中使用幾個函式找到。在下面的例子中,我們將處理使用以下程式碼段建立的 DataFrame。

import pandas as pd import numpy as np  np.random.seed(0)  df = pd.DataFrame(np.random.randint(1, 20, size=(20, 4)), columns=list("ABCD"))  print(df) 

輸出:

 A B C D 0 13 16 1 4 1 4 8 10 19 2 5 7 13 2 3 7 8 15 18 4 6 14 9 10 5 17 6 16 16 6 1 19 4 18 7 15 8 1 2 8 10 1 11 4 9 12 19 3 1 10 1 5 6 7 11 9 18 16 5 12 10 11 2 2 13 8 10 4 7 14 12 15 19 1 15 15 4 13 11 16 12 5 7 5 17 16 4 13 5 18 9 15 16 4 19 16 14 17 18 

在 Pandas 中獲取包含整數/浮點數的行的索引

pandas.DataFrame.loc 函式可以通過其標籤/名稱訪問行和列。它直接返回與作為標籤傳遞的給定布林條件相匹配的行。請注意片段中 df.loc 旁邊的方括號。

import pandas as pd import numpy as np  np.random.seed(0)  df = pd.DataFrame(np.random.randint(1, 20, size=(20, 4)), columns=list("ABCD"))  print(df.loc[df["B"] == 19]) 

對應於布林條件的行將以 Dataframe 格式的輸出返回。

輸出:

 A B C D 6 1 19 4 18 9 12 19 3 1 

多個條件可以被串聯起來並一起應用到函式中,如下所示。這有助於根據特定條件隔離行。

import pandas as pd import numpy as np  np.random.seed(0)  df = pd.DataFrame(np.random.randint(1, 20, size=(20, 4)), columns=list("ABCD"))  print(df.loc[(df["B"] == 19) | (df["C"] == 19)]) 

輸出:

 A B C D 6 1 19 4 18 9 12 19 3 1 14 12 15 19 1 

pandas.DataFrame.index() 獲取行的索引

如果你想只查詢滿足作為引數傳遞的布林條件的 DataFrame 的匹配索引,pandas.DataFrame.index() 是最簡單的實現方式。

import pandas as pd import numpy as np  np.random.seed(0)  df = pd.DataFrame(np.random.randint(1, 20, size=(20, 4)), columns=list("ABCD"))  print(df.index[df["B"] == 19].tolist()) 

在上面的程式碼段中,列 A 中與布林條件 == 1 相匹配的行以輸出的方式返回,如下所示。

輸出:

[6, 9] 

我們之所以把 tolist() 放在 index() 方法後面,是為了把 Index 轉換為列表,否則,結果就是 Int64Index 資料型別。

Int64Index([6, 9], dtype='int64' 

也可以根據多個條件只檢索索引。這段程式碼可以寫成如下。

import pandas as pd import numpy as np  np.random.seed(0)  df = pd.DataFrame(np.random.randint(1, 20, size=(20, 4)), columns=list("ABCD"))  print(df.index[(df["B"] == 19) | (df["C"] == 19)].tolist()) 

輸出:

[6, 9, 14] 

在 Pandas 中獲取包含字串的行的索引

字串值可以根據兩種方法進行匹配。上一節中所示的兩種方法都可以使用,除了條件變化。

在下面的例子中,我們將使用以下片段。

import pandas as pd  df = pd.DataFrame(  {  "Name": ["blue", "delta", "echo", "charlie", "alpha"],  "Type": ["Raptors", "Raptors", "Raptors", "Raptors", "Tyrannosaurus rex"],  } )  print(df) 

輸出:

 Name Type 0 blue Raptors 1 delta Raptors 2 echo Raptors 3 charlie Raptors 4 alpha Tyrannosaurus rex 

用精確字串匹配獲取行的索引

上一節中使用的相等條件可以用來尋找 Dataframe 中的精確字串匹配。我們來尋找兩個字串。

import pandas as pd  df = pd.DataFrame(  {  "Name": ["blue", "delta", "echo", "charlie", "alpha"],  "Type": ["Raptors", "Raptors", "Raptors", "Raptors", "Tyrannosaurus rex"],  } )  print(df.index[(df["Name"] == "blue")].tolist()) print("\n") print(df.loc[df["Name"] == "blue"]) print("\n") print(df.loc[(df["Name"] == "charlie") & (df["Type"] == "Raptors")]) 

輸出:

[0]   Name Type 0 blue Raptors   Name Type 3 charlie Raptors 

如上所示,索引和符合條件的行都可以被接收。

獲取具有部分字串匹配條件的行的索引

通過將 DataFrame 與 str.contains 函式進行鏈式連線,可以部分匹配字串值。在下面的例子中,我們將在 charlie 和 alpha中尋找字串 ha

import pandas as pd  df = pd.DataFrame(  {  "Name": ["blue", "delta", "echo", "charlie", "alpha"],  "Type": ["Raptors", "Raptors", "Raptors", "Raptors", "Tyrannosaurus rex"],  } )  print(df.index[df["Name"].str.contains("ha")].tolist()) print("\n") print(df.loc[df["Name"].str.contains("ha")]) print("\n") print(df.loc[(df["Name"].str.contains("ha")) & (df["Type"].str.contains("Rex"))]) 

輸出:

[3, 4]   Name Type 3 charlie Raptors 4 alpha Tyrannosaurus rex    Name Type 4 alpha Tyrannosaurus rex 

這個函式在對 DataFrame 的多列進行部分字串匹配時非常有用。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相關文章 - Pandas DataFrame

相關文章 - Pandas DataFrame Row