檢查 Pandas DataFrame 中列是否以給定字串開頭/結尾


Pandas 是一個流行的 Python 庫,用於資料操作和分析。它提供了強大的工具來處理結構化資料,例如表格或電子表格。Pandas 可以處理各種資料格式,包括 CSV、Excel、SQL 資料庫和 JSON 等。

Pandas 的一個關鍵特性是其兩個主要的資料結構:Series 和 DataFrame。

Series 是一種一維陣列狀物件,可以儲存任何資料型別,例如整數、浮點數、字串,甚至是 Python 物件。Series 帶有標籤,這意味著它們有一個索引,用於訪問和操作資料。

DataFrame 是一種二維表格狀資料結構,具有行和列,類似於電子表格或 SQL 表格。它可以包含多種資料型別,可以被認為是 Series 的集合。DataFrame 非常強大和靈活,因為它們可以透過多種方式進行操作,例如過濾、合併、分組和轉換資料。

Pandas 提供了許多用於處理 DataFrame 的工具,包括用於索引、選擇和過濾資料的方法,以及統計和數學運算。Pandas 還包括處理缺失資料、重塑資料和處理時間序列資料的工具。

要建立一個 DataFrame,您可以將字典或列表的列表傳遞給 DataFrame 建構函式。字典中的每個鍵代表 DataFrame 中的一列,而值代表該列中的資料。或者,您可以從 CSV、Excel、SQL 資料庫或其他資料格式建立 DataFrame。

總而言之,Pandas 是一個功能強大且靈活的庫,用於處理 Python 中的結構化資料,其 DataFrame 資料結構是其最重要的功能之一。憑藉其廣泛的功能和易用性,Pandas 對於任何使用 Python 處理資料的資料科學家或分析師來說都是一個必不可少的工具。

現在我們詳細瞭解了 pandas 和 pandas DataFrame,讓我們簡單瞭解一下 Pandas endswith() 方法。

endswith()

Pandas 中的 endswith() 方法也可以應用於 DataFrame,以檢查指定列中的每個元素是否以給定的字串或字元結尾。該方法返回一個布林 DataFrame 物件,其形狀與原始 DataFrame 相同。

在 Pandas 中使用 endswith() 方法與 DataFrame 的語法如下:

DataFrame[column_name].str.endswith(suffix, na=None)

其中 DataFrame 是您要應用該方法的 DataFrame 的名稱,column_name 是您要檢查 endswith 條件的列的名稱,suffix 是您要檢查列中每個元素是否以其結尾的字串或字元序列,na 是一個可選引數,用於指定如何處理缺失值或空值。

為了說明這一點,讓我們考慮一個包含員工資訊(例如“員工 ID”、“姓名”、“部門”和“薪水”)的員工資料集的示例。

示例

# Importing the pandas library and renaming it as pd
import pandas as pd

# Creating a DataFrame for employees
employee_df = pd.DataFrame({
    'Employee_ID': ['E101', 'E102', 'E103', 'E104', 'E105'],
    'Name': ['John', 'Emily', 'Mark', 'Sarah', 'Jessica'],
    'Department': ['Sales', 'HR', 'IT', 'Marketing', 'Finance'],
    'Salary': [50000, 60000, 75000, 80000, 90000]
})

# Printing the original DataFrame
print("Printing Original Employee DataFrame:")
print(employee_df)

解釋

這段程式碼使用 Pandas 庫從字典建立一個 DataFrame。以下是程式碼各個部分的作用:

  • import pandas as pd:這行程式碼匯入 Pandas 庫,並將其重新命名為“pd”,以便我們可以更輕鬆地在程式碼中引用它。

  • data = {'name': ['John', 'Emily', 'Mark', 'Jessica'], 'age': [25, 32, 18, 47], 'country': ['USA', 'Canada', 'UK', 'USA'], 'gender': ['M', 'F', 'M', 'F']}: 這行程式碼建立一個名為“data”的字典,其鍵為“name”、“age”、“country”和“gender”。每個鍵都有一個值列表,對應於該列的資料。

  • df = pd.DataFrame(data): 這行程式碼根據字典“data”建立一個名為“df”的 DataFrame。Pandas 會自動使用字典的鍵作為 DataFrame 的列標題,並將每個列表中的值作為相應列中的值。

  • print(df):這行程式碼將 DataFrame 列印到控制檯。輸出將如下所示:

要執行上述程式碼,我們需要執行下面顯示的命令。

命令

python3 main.py

輸出

Printing Original Employee DataFrame:
  Employee_ID     Name Department  Salary
0        E101     John      Sales   50000
1        E102    Emily         HR   60000
2        E103     Mark         IT   75000
3        E104    Sarah  Marketing   80000
4        E105  Jessica    Finance   90000

現在讓我們在上述程式碼中使用 endswith() 方法。

在第一個示例中,我們將檢查 DataFrame 列“Department”是否包含“IT”。

考慮下面顯示的程式碼。

示例

# Importing the pandas library and renaming it as pd
import pandas as pd

# Creating a DataFrame for employees
employee_df = pd.DataFrame({
    'Employee_ID': ['E101', 'E102', 'E103', 'E104', 'E105'],
    'Name': ['John', 'Emily', 'Mark', 'Sarah', 'Jessica'],
    'Department': ['Sales', 'HR', 'IT', 'Marketing', 'Finance'],
    'Salary': [50000, 60000, 75000, 80000, 90000]
})

# Printing the original DataFrame
print("Printing Original Employee DataFrame:")
# print(employee_df)

# Applying a lambda function to each value in the "Department" column
# The lambda function uses the `endswith()` string method to check if the string ends with "IT"
# The `map()` function applies the lambda function to each value in the column and returns a list of boolean values
# The list is used to create a new column in the `employee_df` DataFrame
employee_df['TutorialsPoint_Emp'] = list(
	map(lambda x: x.endswith('IT'), employee_df['Department']))

# Printing the new DataFrame with the added column
print(employee_df)

在這種情況下,endswith() 函式用於執行條件檢查並根據該檢查的結果建立新列。它是資料操作和過濾的有用工具,尤其是在處理文字資料時。

這段程式碼的輸出將是一個修改後的 DataFrame,其中包含一個名為“TutorialsPoint_Emp”的新列。此列包含布林值,指示員工是否在 IT 部門工作 (True) 或不工作 (False)。輸出將如下所示:

要執行上述程式碼,我們需要執行下面顯示的命令。

命令

python3 main.py

輸出

Printing Original Employee DataFrame:
  Employee_ID     Name Department  Salary  TutorialsPoint_Emp
0        E101     John      Sales   50000              False
1        E102    Emily         HR   60000               False
2        E103     Mark         IT   75000                True
3        E104    Sarah  Marketing   80000          False
4        E105  Jessica    Finance   90000          False

現在讓我們嘗試在另一列上使用 endswith() 方法。

考慮下面顯示的程式碼。

示例

# Importing the pandas library and renaming it as pd
import pandas as pd

# Creating a DataFrame for employees
employee_df = pd.DataFrame({
    'Employee_ID': ['E101', 'E102', 'E103', 'E104', 'E105'],
    'Name': ['John', 'Emily', 'Mark', 'Sarah', 'Jessica'],
    'Department': ['Sales', 'HR', 'IT', 'Marketing', 'Finance'],
    'Salary': [50000, 60000, 75000, 80000, 90000]
})

# Printing the original DataFrame
print("Printing Original Employee DataFrame:")
# print(employee_df)

# joining new column in dataframe
# endwith function used to check
employee_df['TutorialsPoint_Emp'] = list(
	map(lambda x: x.endswith('Sarah'), employee_df['Name']))
	
# printing new data frame
print(employee_df)

解釋

在上面的程式碼中,我們使用了 map() 函式和 lambda 函式來檢查每個員工的姓名是否以字串“Sarah”結尾。這是使用 endswith() 方法完成的,該方法返回一個布林值,指示給定字串是否以指定的字尾結尾。

然後,將生成的布林值使用 list() 函式轉換為列表,並存儲在 DataFrame 的名為“TutorialsPoint_Emp”的新列中。

最後,使用 print() 函式列印修改後的 DataFrame。輸出將顯示原始員工資訊以及指示每個員工的姓名是否以“Sarah”結尾的新列。

要執行上述程式碼,我們需要執行下面顯示的命令。

命令

python3 main.py

輸出

Printing Original Employee DataFrame:
  Employee_ID     Name Department  Salary  TutorialsPoint_Emp
0        E101     John      Sales   50000               False
1        E102    Emily         HR   60000               False
2        E103     Mark         IT   75000               False
3        E104    Sarah  Marketing   80000                True
4        E105  Jessica    Finance   90000               False

結論

總而言之,Pandas DataFrame 中的 endswith() 方法允許我們檢查給定列的元素是否以指定的 suffix 結尾。此方法可用於根據 DataFrame 列中存在的某些字串模式來操作資料。透過使用 endswith() 方法,我們可以根據特定條件過濾和轉換資料,使其成為資料分析和資料清理任務的有用工具。

更新於:2023年8月2日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.