簡體   English   中英

如何使用for循環過濾Pandas數據框列中的字符串

[英]How to filter a string in a column of Pandas data frame using for loop

如何在 Pandas 數據框的字符串過濾中使用“for”循環(例如“ for i in range(1996,2000,1) ”)?

我有一個這樣的數據框:

Date            Value
07/09/1997      505
05/03/1998      1005
03/02/2000      747
01/05/1998      448
06/08/1996      57
09/11/2000      673

我喜歡使用 ' for i in range(1996,2000,1) ' 循環從 'Date' 列中過濾 '1998' 並創建一個新的 DF,使其看起來像這樣:

Date            Value
05/03/1998      1005
01/05/1998      448

for循環較慢,最好盡可能避免

使用pd.to_datetimeDate列轉換為datetime pd.to_datetime ,然后使用Series.dt.year僅提取year

In [2441]: df.Date = pd.to_datetime(df.Date)
In [2446]: df = df[df.Date.dt.year.eq(1998)]

In [2447]: df
Out[2447]: 
        Date  Value
1 1998-05-03   1005
3 1998-01-05    448

此外,根據@CainãMaxCouto-Silva 的評論:

您還可以過濾一系列年份:

In [2451]: df[df.Date.dt.year.isin(range(1996,2000))]
Out[2451]: 
        Date  Value
0 1997-07-09    505
1 1998-05-03   1005
3 1998-01-05    448
4 1996-06-08     57

其它的辦法

df.Date = pd.to_datetime(df.Date)
df[df.Date.dt.isocalendar().year.eq(1998)]



        Date  Value
1 1998-05-03   1005
3 1998-01-05    448

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM