首頁  >  文章  >  後端開發  >  如何提取資料框中部分字串匹配的列?

如何提取資料框中部分字串匹配的列?

Barbara Streisand
Barbara Streisand原創
2024-10-20 14:00:03838瀏覽

How to Extract Columns With Partial String Matches in a DataFrame?

尋找部分字串匹配的列

在 DataFrame 中查詢包含特定字串的列可能是有用的操作。但是,如果匹配不精確但包含某個子字串怎麼辦?這就是正規表示式過濾器發揮作用的地方。

要尋找名稱包含特定字串(特別是連續子字串)的列,請考慮以下解決方案:

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

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

# Use regex filter to select columns with 'spike' substring
spike_cols = df.filter(regex='spike').columns.tolist()

# Print the column names with the matching substring
print(spike_cols)</code>

此程式碼迭代DataFrame 的列使用列表理解並應用正規表示式過濾器來尋找具有“spike”子字串的列。然後,產生的列名稱清單將儲存在Spike_cols變數中,該變數可用於根據需要存取對應的列。

另一種方法是將列名稱轉換為列表並迭代它們,測試每個列名稱使用for 循環和if 語句匹配子字串的名稱:

<code class="python"># Column names converted to a list
col_list = list(df.columns)

# Iterate over the column names
for col in col_list:
    if 'spike' in col:
        # Column name with matching substring found
        print(col)</code>

透過使用這些方法,您可以有效地識別和存取DataFrame 中名稱包含特定字串的列,即使它不是完全符合。

以上是如何提取資料框中部分字串匹配的列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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