【问题标题】:How can I filter a data frame with a datetime index by a month and year input? Pandas如何按月份和年份输入过滤具有日期时间索引的数据框?熊猫
【发布时间】:2018-01-02 21:30:15
【问题描述】:

给定一个像这样的df

df=pd.read_csv(PATH + 'Matriz3_fechas.csv',index_col='Fecha',skiprows=0)
df.index = pd.DatetimeIndex(df.index)

注意,Fecha 已经是日期时间格式的索引**

 Fecha                D576972dc305aa  D576972dc32e9a  D576972dc3590a  
                                                             
2016-06-01 00:00:00         0.0          0.0               0.1  
2016-07-01 00:05:00         0.0          0.0               0.1  
2017-05-01 00:10:00         0.0          0.0               0.1  
2017-05-01 00:15:00         0.0          0.0               0.1                                                              
2017-07-01 00:20:00         0.0          0.0               0.1  
                                                                 

我尝试按月份和年份过滤:

df=df[(df.index.month==5)&(matriz.index.year==2017)]

但它不会过滤df 以获得:(期望的结果)

 Fecha                D576972dc305aa  D576972dc32e9a  D576972dc3590a  \
                                                             
2017-05-01 00:10:00         0.0          0.0               0.1  \
2017-05-01 00:15:00         0.0          0.0               0.1  \

【问题讨论】:

    标签: python pandas datetime indexing


    【解决方案1】:

    你可以使用partial string indexing:

    #for datetimeindex use parameter parse_dates 
    df=pd.read_csv(PATH+'Matriz3_fechas.csv',index_col='Fecha',skiprows=0,parse_dates=['Fecha'])
    
    print (df.index)
    DatetimeIndex(['2016-06-01 00:00:00', '2016-07-01 00:05:00',
                   '2017-05-01 00:10:00', '2017-05-01 00:15:00',
                   '2017-07-01 00:20:00'],
                  dtype='datetime64[ns]', name='Fecha', freq=None)
    
    
    df = df.loc['2017-05']
    print (df)
                         D576972dc305aa  D576972dc32e9a  D576972dc3590a
    Fecha                                                              
    2017-05-01 00:10:00             0.0             0.0             0.1
    2017-05-01 00:15:00             0.0             0.0             0.1
    

    但您的解决方案也有效(如果 matrizdf,我认为是错字):

    df=df[(df.index.month==5)&(df.index.year==2017)]
    print (df)
                         D576972dc305aa  D576972dc32e9a  D576972dc3590a
    Fecha                                                              
    2017-05-01 00:10:00             0.0             0.0             0.1
    2017-05-01 00:15:00             0.0             0.0             0.1
    

    【讨论】:

    • 就是这么简单
    • 所以print (df.index) 返回DatetimeIndex?月与日不交换?
    • 我之前尝试过,但输出的形状我得到的是 [0 行 x 3 列] 而不是 [2 行 x 3 列] @jezrael
    • 嗯,这意味着20175月份没有数据。但也许 2017-05-10 被交换为 2017-10-05 所以它过滤错误。你能检查一下吗?
    • @jezreal 发现了问题,我的 .csv 没有更新,所以它没有 2017-05 的数据。不过你的回答对我有帮助。
    猜你喜欢
    • 2016-11-29
    • 2017-06-14
    • 2018-04-03
    • 1970-01-01
    • 2023-03-29
    • 2021-05-03
    • 1970-01-01
    • 2021-09-08
    • 2021-04-26
    相关资源
    最近更新 更多