如何在pandas filter方法中使用正則表示式檢索series物件的行?


透過使用regex引數,我們可以將正則表示式應用於filter()方法,這有助於檢索series物件的指定行。Pandas series建構函式中series.filter()方法的基本工作原理是根據索引標籤對series物件的行進行子集選擇。

regex引數用於定義一個搜尋模式(正則表示式),該模式用於檢索結果行。

示例1

在下面的示例中,我們使用整數列表建立了一個series物件,並使用pandas資料範圍函式建立索引標籤。

# importing pandas package
import pandas as pd

# create date index
index = pd.date_range('2021-08-1', periods=10, freq='10H30min40s')

#creating pandas Series with date-time index
series = pd.Series([1,2,3,4,5,6,7,8,9,10], index=index)

print(series)

print("Output: ")
# Apply the filter method with regex
print(series.filter(regex='40$'))

解釋

在這裡,我們透過使用regex引數指定搜尋模式來過濾pandas series物件中的某些行。

輸出

輸出如下:

2021-08-01 00:00:00    1
2021-08-01 10:30:40    2
2021-08-01 21:01:20    3
2021-08-02 07:32:00    4
2021-08-02 18:02:40    5
2021-08-03 04:33:20    6
2021-08-03 15:04:00    7
2021-08-04 01:34:40    8
2021-08-04 12:05:20    9
2021-08-04 22:36:00    10
Freq: 37840S, dtype: int64

Output:
2021-08-01 10:30:40    2
2021-08-02 18:02:40    5
2021-08-04 01:34:40    8
Freq: 113520S, dtype: int64

我們可以注意到上面的輸出塊,我們已經成功地過濾了索引中包含40秒的series物件的行。

示例2

讓我們再取一個series物件,過濾掉索引標籤名稱中包含空格的行。

# importing pandas package
import pandas as pd

Countrys = ['Brazil','Canada','New Zealand','Iceland', 'India', 'Sri Lanka', 'United    States']
Capitals = [ 'Belmopan','Ottawa','Wellington','Reykjavik', 'New Delhi','Colombo',          'Washington D.C']

#creating pandas Series
series = pd.Series(Capitals, index=Countrys)

print(series)

print("Output: ")
# Apply the filter method with regex
print(series.filter(regex='. .'))

輸出

輸出如下:

Brazil                 Belmopan
Canada                   Ottawa
New Zealand          Wellington
Iceland               Reykjavik
India                 New Delhi
Sri Lanka               Colombo
United States    Washington D.C
dtype: object

Output:
New Zealand        Wellington
Sri Lanka             Colombo
United States  Washington D.C
dtype: object

在上面的輸出中,我們已經成功地從series物件中過濾掉了名為“紐西蘭”、“斯里蘭卡”、“美國”的幾行。

更新於:2022年3月7日

226 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.