首頁  >  文章  >  後端開發  >  如何使用正規表示式迭代提取 pandas DataFrame 中匹配子字串的列?

如何使用正規表示式迭代提取 pandas DataFrame 中匹配子字串的列?

Susan Sarandon
Susan Sarandon原創
2024-10-20 13:58:29494瀏覽

How to Extract Columns with Matching Substrings in pandas DataFrame Iteratively and Using Regular Expressions?

識別包含特定子字串的列

要定位名稱包含指定子字串而不需要精確匹配的列,可以採用迭代方法。這涉及檢查每個列名稱並識別那些滿足搜尋條件的列名稱。

考慮一個具有列名稱(例如「spike-2」、「hey spike」和「spiked-in」)的 DataFrame。要擷取包含子字串「spike」的欄位名稱,可以使用下列Python程式碼:

<code class="python">import pandas as pd

# Initialize data
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)

# Iterate over column names and filter based on substring
spike_cols = [col for col in df.columns if 'spike' in col]

# Print resulting column names
print(spike_cols)</code>

在此程式碼中:

  1. df.columns 傳回列的清單
  2. 列表理解[col for col in df.columns if 'spike' in col] 使用變數col 迭代每個列名稱,並建構一個僅包含包含子字串'spike' 的名稱的新列表.
  3. 產生的spike_cols 包含所需的欄位名稱,稍後可以使用df['col_name'] 或df[col_name] 存取。

或者,透過以下方式取得 DataFrame僅符合資料列:

<code class="python">df2 = df.filter(regex='spike')</code>

這將建立僅包含名稱包含「spike」的資料列的 df2。

以上是如何使用正規表示式迭代提取 pandas DataFrame 中匹配子字串的列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn