过去四个季度的数据帧筛选。

huangapple go评论73阅读模式
英文:

Filter dataframe for past 4 quarters

问题

我有一个包含起始日期和结束日期的DataFrame,首先我需要使用结束日期创建一个新列,该列包含年季度(2022Q4),我使用以下代码实现:

df['Quarter'] = pd.PeriodIndex(df['End Date'], freq='Q')

现在,我想要使用结束日期来筛选过去四个季度的数据,假设当前是2023Q1,所以我想要筛选数据,以便获得(2022Q1,2022Q2,2022Q3,2022Q4)的数据。

我该如何在Python中实现这个目标?

英文:

I have a DataFrame with start date and end date as a column. Firstly I need create a new column using End Date which consists of yearquarter (2022Q4) which I did using below code:

df['Quarter']=pd.PeriodIndex(d['End Date'],freq='Q')

Now I want to filter data for past 4 quarters using End Date, lets say curremtly its 2023Q1, so I want to filter so That I can get data for (2022Q1, 2022Q2, 2022Q3, 2022Q4).

How can I achieve this in python.

答案1

得分: 1

使用 Serie.dt.to_period 来生成实际季度,通过 TimestampTimestamp.to_period 生成,然后使用 boolean indexingSeries.between 进行最后的筛选:

df = pd.DataFrame({'End Date': pd.date_range('2021-12-01', freq='25D', periods=20)})

df['Quarter'] = df['End Date'].dt.to_period('q')

now = pd.Timestamp.now().to_period('q')

out = df[df['Quarter'].between(now - 4, now - 1)]
print(out)

输出结果如下:

     End Date Quarter
2  2022-01-20  2022Q1
3  2022-02-14  2022Q1
4  2022-03-11  2022Q1
5  2022-04-05  2022Q2
6  2022-04-30  2022Q2
7  2022-05-25  2022Q2
8  2022-06-19  2022Q2
9  2022-07-14  2022Q3
10 2022-08-08  2022Q3
11 2022-09-02  2022Q3
12 2022-09-27  2022Q3
13 2022-10-22  2022Q4
14 2022-11-16  2022Q4
15 2022-12-11  2022Q4
英文:

Use Serie.dt.to_period for quarters with generate actual quarter by Timestamp and Timestamp.to_period, last filter by boolean indexing with Series.between:

df = pd.DataFrame({'End Date':pd.date_range('2021-12-01', freq='25D', periods=20)})
    
df['Quarter'] = df['End Date'].dt.to_period('q')

now = pd.Timestamp.now().to_period('q')

out = df[df['Quarter'].between(now - 4, now - 1)]
print (out)
     End Date Quarter
2  2022-01-20  2022Q1
3  2022-02-14  2022Q1
4  2022-03-11  2022Q1
5  2022-04-05  2022Q2
6  2022-04-30  2022Q2
7  2022-05-25  2022Q2
8  2022-06-19  2022Q2
9  2022-07-14  2022Q3
10 2022-08-08  2022Q3
11 2022-09-02  2022Q3
12 2022-09-27  2022Q3
13 2022-10-22  2022Q4
14 2022-11-16  2022Q4
15 2022-12-11  2022Q4

huangapple
  • 本文由 发表于 2023年2月14日 18:43:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定