【问题标题】:How to use a variable with multiple possible formats in loc to slice a pandas dataframe with a DatetimeIndex如何在 loc 中使用具有多种可能格式的变量来切片带有 DatetimeIndex 的 pandas 数据帧
【发布时间】:2019-09-18 15:08:46
【问题描述】:

我需要定义一个函数,该函数将对包含 DatetimeIndex 的数据帧执行多项操作。其中一项操作是根据作为函数参数之一传递的时间段或日期对数据帧进行切片。

在代码中使用 loc 时,切片对象接受不同的选项。例如:

df.loc['2004'] 

对所有日期为 2004 年的行进行切片

df.loc['2004-01':'2005-02'] 

对日期在 2004 年 1 月到 2005 年 2 月之间的所有行进行切片

我希望能够只使用函数的一个参数来构造 loc[] 内部的切片对象。比如:

df.loc[period] 

其中句点是作为参数之一传递给函数的变量,可以以不同的格式定义,以便函数正确解释。

我试过了:

  • 将字符串变量传递给 loc,例如构造为 "\'2004\'"+':'+"\'2005\'" 的值,但它返回 KeyError "'2002': '2010'”。

  • 使用 pd.to_datetime 将字符串转换为日期时间对象。但这会导致“2004”转换为 Timestamp('2004-01-01 00:00:00')

我发现 this answerthis answer 很相似,但并不特定于我的需要。

我可以在函数中使用两个参数来解决这个问题(比如 start_date、end_date),但我想知道是否有办法只用一个来实现。

【问题讨论】:

    标签: python pandas string datetimeindex pandas-loc


    【解决方案1】:

    slice 内置应该适用于此:

    # equivalent to df.loc['2004':]
    period = slice('2004', None)
    df.loc[period]
    
    # equivalent to df.loc['2004-01':'2005-02'] 
    period = slice('2004-01', '2005-02')
    df.loc[period]
    

    【讨论】:

    • 谢谢,我想这肯定提供了一种方法来构造另一个内部函数来解释传递的字符串参数,然后在 loc 中使用它。例如,如果用户只传递 '2004' 作为参数,这意味着只对 2004 年的所有日期进行切片,则等效为 period=slice('2004','2004')。
    • 我认为应该可以。另外,如果用户只通过'2004',你根本不需要切片:]
    • 我的意思是你可以做到period='2004'
    • 你是完全正确的,我已经检查过了,并且 period='2004' 或 period "2004-10" 在 df.loc[period] 中工作,但不是像 "2004:2005" 这样的字符串" 或 "\'2004\'"+':'+"\'2005\'"。
    猜你喜欢
    • 2021-08-01
    • 2020-11-25
    • 2021-03-19
    • 2021-05-20
    • 1970-01-01
    • 2019-10-25
    • 2020-07-06
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多