【问题标题】:Loop for starting month and starting year to end month and year python循环开始月份和开始年份到结束月份和年份python
【发布时间】:2020-01-04 14:02:14
【问题描述】:

数据库df:

month    year   data
Jan      2017    ggg
Feb      2015    jhjj
Jan      2018    hjhj
Mar      2018    hjhj

and so on

代码:

def data_from_start_month_to_end_month:
    for y in range(start_year,end_year):
        do something 
        for m in range(start_month,13):
            df = df[(df['month'] == m)&(df['year']== y)]
    return df        

这将从起始月份和年份开始代码,但如果结束月份不是 12 月,那么它将不起作用。

我想要的输出:

start_month = Sep 
start_year = 2000
end_month = Feb
end_year = 2019 say

所以循环应该在 2000 年 9 月到 2019 年 2 月期间工作,并且只提取那些行的数据。(但我需要函数是通用的,而不是硬编码的

谁能帮忙

【问题讨论】:

  • 您需要结合月份和年份列来创建一系列datetime Series - 然后为您的开始日期和结束日期创建日期时间对象,然后进行比较。

标签: python pandas date for-loop calendar


【解决方案1】:

在将输入转换为日期时间后,您可以使用以下使用series.between 的函数:

def myf(df,start_month,start_year,end_month,end_year):
    s= pd.to_datetime(df['month']+df['year'].astype(str),format='%b%Y')
    start = pd.to_datetime(start_month+str(start_year),format='%b%Y')
    end = pd.to_datetime(end_month+str(end_year),format='%b%Y')
    return df[s.between(start,end)]

myf(df,'Sep',2000,'Feb',2017)

  month  year  data
0   Jan  2017   ggg
1   Feb  2015  jhjj

如果月份是数字,请使用format='%m%Y' 而不是format='%b%Y'

def myf1(df,start_month,start_year,end_month,end_year):
    s= pd.to_datetime(df['month'].astype(str)+df['year'].astype(str),format='%m%Y')
    start = pd.to_datetime(start_month+str(start_year),format='%b%Y')
    end = pd.to_datetime(end_month+str(end_year),format='%b%Y')
    return df[s.between(start,end)]

例子df:

   month  year  data
0      1  2017   ggg
1      2  2015  jhjj
2      1  2018  hjhj
3      3  2018  hjhj

myf1(df,'Sep',2000,'Feb',2017)

   month  year  data
0      1  2017   ggg
1      2  2015  jhjj

【讨论】:

  • 如果月份是数字怎么办让我们说 1,2.....12 等。那么这将如何工作
  • @ShailajaGuptaKapoor 只需更改格式参数即可实现,但需要确认:因此,如果月份为数字,您仍希望输入 Jan 作为输入参数而不是 1?
  • @ShailajaGuptaKapoor 编辑了我的答案。您可以从here获得所有格式提示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
相关资源
最近更新 更多